C++ 输出字符串数组
我试图在字符串上打印一些值,如下所示:C++ 输出字符串数组,c++,C++,我试图在字符串上打印一些值,如下所示: std::vector<std::string> data; data.push_back("One"); data.push_back("1"); const std::string & description = "This %s is number %s"; DWORD dwSize = data.size(); char szDescription[255 + 1]; for (DWORD i = 0; i <
std::vector<std::string> data;
data.push_back("One");
data.push_back("1");
const std::string & description = "This %s is number %s";
DWORD dwSize = data.size();
char szDescription[255 + 1];
for (DWORD i = 0; i < dwSize; ++i)
{
_snprintf(szDescription, sizeof(szDescription), description.c_str(), data[i].c_str());
}
return szDescription;
我在
snprintf
之后打印字符串,第二个值在第一次迭代中处理另一种解决方案是逐个替换std::string
中的令牌。您可以使用不同的解决方案(例如,使用正则表达式、使用类库等)。下面是一个使用基本std::string
方法的简单示例:
#include <iostream>
#include <vector>
std::string build() {
std::vector<std::string> data;
data.push_back("One");
data.push_back("1");
const std::string token = "%s";
const std::string description = "This %s is number %s";
std::string out = "";
size_t start = 0;
size_t end = description.find(token);
int i = 0;
while (end != std::string::npos) {
out += description.substr(start, end - start);
out += data[i++];
start = end + token.length();
end = description.find(token, start);
}
out += description.substr(start, end - start);
return out;
}
int main () {
std::cout << build() << '\n';
return 0;
}
因为这是C++,你可以使用。<>代码> ySNPrTNF的问题是它不是类型安全的(输入类型必须与格式说明符匹配),而且它对C++对象一无所知,例如<代码> STD::String
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
std::string foo()
{
std::vector<std::string> data;
data.push_back("One");
data.push_back("1");
std::ostringstream strm;
std::string s;
for (size_t i = 0; i < data.size(); ++i)
{
strm << "The " << data[i] << " is number " << i + 1;
s = strm.str();
std::cout << s << "\n";
strm.str("");
}
return s;
}
int main()
{
foo();
}
\u snprintf()
和char[]
与std::string
混合使用?只是为什么?不用于在C++中使用字符串和字符,如果你可以引用“代码> C代码/代码>函数,如C
概念,给出的答案基本上是如何放弃这些概念。另外,看看这个答案和Hugotixera给出的结果有什么区别?抱歉,我太困了,目标是格式化,而不是连接,假设字符串和值是由一个经过解析的文本脚本给出的,这就是为什么他的示例适用于这个问题,但是,如果有一个使用ostringstream
的解决方案,当然不需要进行拆分,效果会更好
This One is number 1
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
std::string foo()
{
std::vector<std::string> data;
data.push_back("One");
data.push_back("1");
std::ostringstream strm;
std::string s;
for (size_t i = 0; i < data.size(); ++i)
{
strm << "The " << data[i] << " is number " << i + 1;
s = strm.str();
std::cout << s << "\n";
strm.str("");
}
return s;
}
int main()
{
foo();
}
The One is number 1
The 1 is number 2