简体   繁体   English

从文件读取整数时发生无限循环

[英]Infinite loop while reading integers from file

I have two files. 我有两个文件。 main.cpp: main.cpp中:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream file;
    file.open("file.txt");

    if (!file.good()) {
        cout << "Error." << endl;
        return 1;
    }

    int n;
    while (!file.eof()) {
        file.clear();

        file >> n;
        if (!file.good() && !file.bad()) {
            continue;
        } else {
            cout << "Hardware error." << endl;
            break;
        }
        cout << n << endl;
    }

    file.close();

    return 0;
}

and file.txt: 和file.txt:

a 1 2 321b9 ac.de ef#@g 5 #3

I'd like to read only integers from this file and write them out to the console. 我只想从此文件中读取整数,然后将其写到控制台。 When file contains only integers program works well but when it contains any invalid characters then I get infinite loop. 当文件仅包含整数时,程序运行良好,但是当包含任何无效字符时,则出现无限循环。 How can I fix that? 我该如何解决?

The loop is because the stream doesn't extract the character that is not an integer. 循环是因为流不会提取不是整数的字符。 You need to extract it before attempting to read another integer. 您需要先提取它,然后再尝试读取另一个整数。

A small tweak could be all that is needed; 可能只需要进行一些小的调整即可;

// on a failed read...
file.clear();
char dummy;
file >> dummy;
continue;

A side note on the use of while (!file.eof()) ; 关于while (!file.eof())的使用的注释; it is generally not recommended to do this. 通常不建议这样做。 There are several Q&A on SO on this issue. 关于此问题,有一些关于SO的问答。

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

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