簡體   English   中英

如何在從文件中讀取整數時使用 file.eof()?

[英]How to use file.eof() while reading in integers from a file?

我正在編寫一個從文件中讀取數據的程序。 該文件包含整數行,例如

5 6 2 8 6 7

2 5 3

4 0 9 1 3

每行的第一個整數對應於該行中有多少個數字。 我的目標是讀取每一行,將數字存儲在一個向量中,並對它們進行一些操作。 這是我所做的:

int main(){

 vector<int> vec;
 int amount;
 int nums;
 ifstream file ("file.txt");


 while(!(file.eof())){
     file >> amount;
     cout << amount << endl;

     for (int i = 0; i < amount; i++){
         file >> nums;
         vec.push_back(nums);
     }

 printArray(vec);
 bubbleSort(vec);
 vec.clear();
 }

 return 0;
}

不幸的是,最后一行總是被讀取兩次。 我在網上看了一下,發現 eof() 函數不應該用於維護循環。 在這種情況下我還能用什么?

謝謝。

operator>>設置流的eofbit標志,如果它試圖讀取超過EOF。 您可以使用該條件來打破循環。 但是在評估eof()之前,您必須實際執行讀取操作。 請參閱為什么 iostream::eof 在循環條件內(即`while (!stream.eof())`)被認為是錯誤的? 有關更多詳細信息。

由於您正在處理基於行的文本,因此您可以先使用std::getline()讀取每一行,然后您可以使用std::istringstream來解析每一行,例如:

int main()
{
    vector<int> vec;
    ifstream file ("file.txt");
    string line;

    while (getline(file, line)) {
        istringstream iss(line);
        int amount, nums;

        iss >> amount;
        cout << amount << endl;

        for (int i = 0; (i < amount) && (iss >> nums); ++i){
            vec.push_back(nums);
        }

        printArray(vec);
        bubbleSort(vec);
        vec.clear();
    }

    return 0;
}

或者,您可以簡單地利用operator>>跳過空格的事實,包括換行符,例如:

int main()
{
    vector<int> vec;
    int amount, nums;
    ifstream file ("file.txt");

    while (file >> amount) {
        cout << amount << endl;

        for (int i = 0; (i < amount) && (file >> nums); ++i){
            vec.push_back(nums);
        }

        printArray(vec);
        bubbleSort(vec);
        vec.clear();
    }

    return 0;
}

雖然,與std:getline()方法相比,這種方法對輸入數據中的錯誤的彈性std:getline() 如果給定行中的實際數字數量與該行開頭的指定數量不匹配,則此方法將使其對文件的讀取不同步。 更糟糕的是,如果給定的行包含任何非整數值,這種方法將根本無法讀取任何后續數據。

std:getline()方法中,如果給定的行格式錯誤,代碼將簡單地移動到下一行並繼續像沒有發生任何壞事一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM