2016-04-15 6 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"を1行のテキストとして考えることはできません。そうではない。これは2行のテキストです。

読書の戦略を少し変更する必要があります。

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

あなたはその後、予めwords[]エントリを印刷するnewline_after_word_indexからインデックスを使用することができ....

+0

実際に私はあなたが私のプログラムでそれを実装することができ、ベクターの見当がつかない。可能なら。ありがとうございました –

+1

@DineshKumarプログラムで 'std :: vector'を使うために必要なのは、一番上に' #include 'です。 'std :: vector'はあなたが使っていた配列によく似ていますが、サイズを変更することができます。新しい項目を最後まで' push_back() 'するだけで、必要に応じてメモリを増やすことができます。配列のような要素にアクセスするために 'words [i]'を使用することはできます。 (あなたは良い入門的なC++の本を手に入れるべきです)。 –

関連する問題