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

问题描述 投票:0回答:1
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循环不是应该在到达文件结束时结束吗? 另外,我甚至还不确定它的计数是否正确。

c++ oop file-io
1个回答
0
投票

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

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

然后你只需将文件作为参数传入你的可执行文件中,就像这样。

exec < filename

如果你想走你正在走的路,那么你可以把你的while循环条件替换为 !inputHandle.eof() && std::getline(inputHandle, someStringHere) 然后继续检查是否 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();
}


© www.soinside.com 2019 - 2024. All rights reserved.