繁体   English   中英

while循环后如何继续阅读?

[英]How to keep reading after while loop?

我有一个.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 (当它尝试从第二行读取'$' )。 如果该位置1,则无法从流中读取更多内容。 您需要清除流状态。

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

一种可能的解决方案是改为读取 使用例如std::getline读取一行。 将行放入std::istringstream ,并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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM