簡體   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