在标准输出上格式化矢量字符串

Format vector string on stdout

本文关键字:字符串 格式化 标准输出      更新时间:2023-10-16

所以对于这个程序,我正在为类编写,我必须将向量字符串格式化为标准输出。我知道如何使用'printf'函数来使用字符串,但我不明白如何使用这个。

这是我得到的:

void put(vector<string> ngram){
while(!(cin.eof())){ ///experimental. trying to read text in string then output in stdout. 
printf(ngram, i);///

好吧,我不能从你的问题中读出很多,但从我的理解,你想打印一个字符串向量到标准输出!它将像这样工作:

void put(std::vector<std::string> ngram){
   for(int i=0; i<ngram.size(); i++)
   {
      //for each element in ngram do:
      //here you have multiple options:
      //I prefer std::cout like this:
      std::cout<<ngram.at(i)<<std::endl;
      //or if you want to use printf:
      printf(ngram.at(i).c_str());
   }
   //done...
   return;
}

这是你想要的吗?

如果你只是想让每一项在一行上:

void put(const std::vector<std::string> &ngram) {
    // Use an iterator to go over each item in the vector and print it.
    for (std::vector<std::string>::iterator it = ngram.begin(), end = ngram.end(); it != end; ++it) {
        // It is an iterator that can be used to access each string in the vector.
        // The std::string c_str() method is used to get a c-style character array that printf() can use.
        printf("%sn", it->c_str());
    }
}