循环后如何继续阅读

How to keep reading after while loop?

本文关键字:继续 何继续 循环      更新时间:2023-10-16

我有一个.txt文件,它的第一行有一个数字和空格序列,我希望读取到向量中。然后在下一行有一个"$"符号。在这之后的一行是另一行,包含一系列数字和空格(就像第一行(,我想把它们读入另一个向量。例如

1 2 3 4 5$4 3 2 1 6

我已经尝试了所有的方法,但在初始while循环读取整数后无法继续读取。我如何越过第二行,读第三行?现在它只输出第一行。目前,这是我的代码:

int main(int argc, const char * argv[]) {
ifstream file(argv[1]); 
if (file.is_open() && file.good()){
int addMe;
vector<int> addMeList;
while(file>>addMe){
cout <<addMe<<endl;
addMeList.push_back(addMe);
}
string skip;
while(file >> skip)
cout << skip << endl;
int searchQuery;
vector<int> searchQueries;
while(file>>searchQuery){
searchQueries.push_back(searchQuery);
}
for (int i=0; i<searchQueries.size();i++)
{
cout << searchQueries[i]<<endl;
}
}
return 0;

}

两个问题:

  1. 第一个循环将导致流failbit被设置(当它试图从第二行读取'$'时(。如果设置了该位,则无法从流中读取更多内容。你需要以清除流状态。

  2. 完成上述操作后,第二个循环将读取文件的其余部分。

一种可能的解决方案是读取。使用例如std::getline读取一行。将该行放入std::istringstream中,并从中读取值。

程序逻辑似乎有缺陷。使用第一个while循环,您逐字逐句地读取整个文件,直到最后(而不是行尾(,之后尝试再次读取失败,评估为false,因此它甚至从未进入其他循环。相反,考虑使用getline逐行读取,然后使用istringstream将其分解为int
以下是我改进它的方法:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>                  // include this header to use istringstream
using namespace std;
int main() {
ifstream file("text.txt");      // my test file; Replace with yours 
if (file.is_open() && file.good()) {
string lineIn;              // general line to read into
int i;                      // general int to read into
vector<int> addMeList;
// int addMe;               // not needed anymore
getline(file, lineIn);      // read a line 1
istringstream istr(lineIn); // string stream we can use to read integers from
while (istr >> i) {
cout << i << endl;
addMeList.push_back(i);
}

// string skip;              // not needed anymore 
getline(file, lineIn);       // skips line 2
// int searchQuery;          // not needed anymore
vector<int> searchQueries;
getline(file, lineIn);       // read a line 2
istringstream istr2(lineIn); // string stream we can use to read integers from
while (istr2 >> i) {
searchQueries.push_back(i);
}
for (int i = 0; i < searchQueries.size(); i++)
{
cout << searchQueries[i] << endl;
}
}
return 0;
}

输入文件:

1 2 3 4 5
$
4 3 2 1 6

输出:

1
2
3
4
5
4
3
2
1
6