C++ printf std :: vector

Seb*_*btm 5 c++ printf vector

我如何在C++中做这样的事情:

void my_print(format_string) {
   vector<string> data;
   //Fills vector
   printf(format_string, data);
}

my_print("%1$s - %2$s - %3$s");
my_print("%3$s - %2$s);
Run Code Online (Sandbox Code Playgroud)

我之前没有解释过.格式字符串由应用程序用户输入.

在C#中,这有效:

void my_print(format_string) {
 List<string> data = new List<string>();
 //Fills list
 Console.WriteLine(format_string, data.ToArray);
}

my_print("{0} - {1} - {2}");
my_print("{2} - {1}");
Run Code Online (Sandbox Code Playgroud)

Joh*_*ing 10

如果您要使用流,您还可以ostream_iterator与循环结构一起使用,如copy:

vector<string> data;
data.assign(10, "hello");

copy( &data[0], &data[3], ostream_iterator<string>(cout, " "));
Run Code Online (Sandbox Code Playgroud)

注意第二个参数copy指向一个结束的结尾.输出:

你好你好你好

  • 您不想使用“&amp;data[0]”和“&amp;data[3]”——标准不保证它能够工作。您应该使用“data.begin()”和“data.end()”来代替。 (2认同)

小智 9

printf("%s - %s - %s", data[0].c_str(), data[1].c_str(), data[2].c_str() );
Run Code Online (Sandbox Code Playgroud)

请注意,您必须转换为C风格的字符串 - printf无法为您执行此操作.

编辑:在回答您修改过的问题时,我认为您必须自己解析格式字符串,因为您必须对其进行验证.printf()不会完成这项工作.


Ken*_*oom 6

升压格式库可能会有所帮助.

#include <boost/format.hpp>
#include <vector>
#include <string>
#include <iostream>
int main(int arc, char** argv){
   std::vector<std::string> array;
   array.push_back("Hello");
   array.push_back("word");
   array.push_back("Hello");
   array.push_back("again");
   boost::format f("%s, %s! %s %s! \n");
   f.exceptions( f.exceptions() &
     ~ ( boost::io::too_many_args_bit | boost::io::too_few_args_bit )  );

   for (std::vector<std::string>::iterator i=array.begin();i!=array.end();++i){
      f = f % (*i);
   }
   std::cout << f;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)


Seb*_*btm 2

我暂时用这个函数解决了:

string format_vector(string format, vector<string> &items)
{   
   int counter = 1;

   replace_string(format,"\\n","\n");
   replace_string(format,"\\t","\t");

   for(vector<string>::iterator it = items.begin(); it != items.end(); ++it) {
        ostringstream stm; stm << counter;
        replace_string(format, "%" + stm.str(), *it);
        counter++;
   }
    return format;
}
Run Code Online (Sandbox Code Playgroud)