2016-11-07 95 views
2

只是爲了理解如何正確讀取,如何讀取文件中的下一個文本,如果我想要讀取每行中的不同字符串。每一行可以有不同的尺寸(1號線可以有3串和2號線可以有100個字符串)閱讀字符串直到行尾

2 //Number of lines 
A AS BPST TRRER 
B AS BP 

我在我的代碼是這樣的嘗試,但我不知道如何檢查程序是到底線。

ifstream fich("thefile.txt"); 

fich >> aux; //Contain number of line 

for(int i=0;i<aux;i++){ //For each line 
    string line; 
    getline(fich, line); 

    char nt; //First in line it's always a char 
    fich >> nt; 

    string aux; 

    while(line != "\n"){ //This is wrong, what expression should i use to check? 
     fich >> aux; 
    //In each read i'll save the string in set 
    } 
} 

所以在最後,我想,套裝包括:{{A,AS,BPST,TRRER} {B,AS,BP}}

感謝。

+0

使用['std :: istringstream'](http://en.cppreference.com/w/cpp/io/basic_istringstream)解析該行。 –

+0

有幫助的閱讀:http://stackoverflow.com/questions/7868936/read-file-line-by-line/7868998#7868998請參閱選項2。 – user4581301

回答

2
while(line != "\n"){ //This is wrong, what expression should i use to check? 

是的,因爲'\n'getline()功能刪除。

使用std::istringstream很容易解析的話任意數量上升到目前的line結束:

string aux; 
std::istringstream iss(line); 
while(iss >> aux) { 
    // ... 
} 

還要注意:

fich >> aux; //Contain number of line 

會留下一個用std::getline()讀取空行,因爲在這種情況下'\n'將從該操作中剩餘(參見Using getline(cin, s) after cin更詳細的信息)。