我有一个文本文件,每行都包含一个整数.我想打开文本平铺并计算文件中的整数数量


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();
}

最新更新