2016-04-15 93 views
2
#include<sstream> 
    #include<iostream> 
    using namespace std; 

    int main(){ 
    string line = "test one two three. \n another one \n"; 
    string arr[8]; 
    cout<<line; 
    int i = 0; 
    stringstream ssin(line); 
    while (ssin.good() && i < 8){ 
     ssin >> arr[i]; 
     ++i; 
    } 
    for(i = 0; i < 8; i++){ 
     cout << arr[i]; 
    } 
    return 0; 
    } 

//現在我想打印剛剛在字符串中的換行符(「\ n」)之前的那些元素。如何檢查字符串數組是否在C++中有換行符?

回答

0

不要以爲"test one two three. \n another one \n"作爲一行文字。不是這樣。這是兩行文字。

你需要改變你的閱讀策略。

int main() 
{ 
    string input = "test one two three. \n another one \n"; 
    string arr[8]; 
    int i = 0; 

    stringstream ssin_1(input); 
    string line; 

    // Read only the tokens from the first line. 
    if (std::getline(ssin_1, line)) 
    { 
     stringstream ssin_2(line); 
     while (ssin_2 >> arr[i] && i < 8) 
     { 
     ++i; 
     } 
    } 

    // Don't print all the elements of arr 
    // Print only what has been read. 
    for(int j = 0; j < i; j++){ 
     cout << arr[j] << " "; 
    } 

    return 0; 
} 
+0

感謝它的工作! –

0

您的ssin >> arr[i]跳過空白,失去了所有知識,其中arr條目後跟換行符。

相反,你可以把輸入線第一,然後的話,同時跟蹤新行:

std::vector<size_t> newline_after_word_index; 
std::vector<std::string> words; 
while (getline(ssin, line)) 
{ 
    std::istringstream line_ss(line); 
    std::string word; 
    while (line_ss >> word) 
     words.push_back(word); 
    newline_after_word_index.push_back(words.size()); 
} 

然後可以使用指數從newline_after_word_index打印出事先words[]進入....

+0

其實我不知道矢量的,你可以在我的程序執行。如果可能的話。謝謝 –

+1

@DineshKumar在程序中使用'std :: vector'所需要做的就是'#include '頂部。一個'std :: vector'與你使用的數組非常相似,但它可以自己調整大小 - 只是'push_back()'新項到最後,如果需要的話它會得到更多的內存。你仍然可以使用'words [i]'來訪問像你的數組一樣的元素。 (你應該得到一本很好的C++入門書)。 –

相關問題