2016-11-07 89 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更详细的信息)。