读取字符串直到行尾

时间:2016-11-07 20:46:55

标签: c++ file ifstream

只是为了理解如何正确阅读,我怎样才能从文件中读取下一个文本,如果我想读取每行中的不同字符串。每行可以有不同的大小(第一行可以有3个字符串,第二行可以有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}}

感谢。

1 个答案:

答案 0 :(得分: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)。

相关问题