输出字符串数组

时间:2018-08-17 01:18:53

标签: 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 < dwSize; ++i)
{
    _snprintf(szDescription, sizeof(szDescription), description.c_str(), data[i].c_str());
}

return szDescription;

但是,当我打印字符串时,它会返回我:

This One is number 124897566

我在snprintf之后打印字符串,第二个值在第一次迭代时处理

2 个答案:

答案 0 :(得分:1)

为您提供的另一种解决方案是一一替换NA中的令牌。您可以使用不同的解决方案(例如,使用正则表达式,使用fmt之类的库等)。这是一个使用基本coding方法的简单示例:

std::string

此代码显示:

std::string

答案 1 :(得分:1)

由于这是C ++,因此可以使用std::ostringstream_snprintf的问题在于它不是类型安全的(输入类型必须与格式说明符匹配),并且它对诸如std::string之类的C ++对象一无所知。

#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

Live Example