2013-06-02 45 views
0

因此,對於我正在爲類編寫的程序,我必須將矢量字符串格式化爲標準輸出。我知道如何用'printf'函數的字符串來完成它,但我不明白如何使用它來完成它。在標準輸出上格式化矢量字符串

這裏就是我的了:

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

不要你的意思'printf'? – Dave

+0

是的,讓我解決這個問題。 – user2421178

+0

你打算做什麼?如果你只是想將矢量字符串格式化爲標準輸出,爲什麼你需要while(!(cin.eof()))? – billz

回答

0

好吧,我不讀了很多你的問題,但是從我的理解,要打印字符串矢量到標準輸出!?這可以這樣工作:

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; 
} 

這就是你想要的嗎?

+0

是的!對不起,如果我很直率地解釋我正在嘗試做什麼。我對此很新。感謝您的幫助。 – user2421178

0

如果你只是想在一行中的每個項目:

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("%s\n", it->c_str()); 

    } 

}