我有一个文本文件,每一行都包含一个整数。我想打开文本块并计算文件中的整数个数

I have a text file with each line containing an integer. I want to open the text tile and count the number of integers in the file

void DataHousing::FileOpen() {
    int count = 0;
    // attempt to open the file with read permission
    ifstream inputHandle("NumFile500.txt", ios::in);

    if (inputHandle.is_open() == true) {
        while (!inputHandle.eof()) {
            count++;
        }

        inputHandle.close();
    }

    else {
        cout << "error";
    }

    cout << count;

}

这会卡在 while 循环中。但是当它到达文件末尾时,while 循环不应该结束吗?另外,我什至不确定它是否正确计数。

一个相当简单的方法是使用 std::cin 代替。假设你想计算文件中整数的数量,你可以像这样使用 while 循环:

int readInt;
int count = 0;
while(std::cin >> readInt){
    count++;
}

然后你只需将文件作为参数传递给你的可执行文件:

exec < filename

如果你更喜欢通过你要去的路线,那么你可以用 !inputHandle.eof() && std::getline(inputHandle, someStringHere) 替换你的 while 循环条件然后继续检查 someStringHere 是否是一个 int 并增加你的计数如果是这样的:

int count = 0;
std::string s;

ifstream inputHandle("NumFile500.txt", ios::in);

if (inputHandle.is_open() == true) {
        while (!inputHandle.eof() && std::getline(inputHandle, s)) {
            if(check to see if it's a number here)
                count++;
        }

        inputHandle.close();
}