我有一个包含动物数据的文件,我读取每一行并将信息处理到我的结构数组中,但问题是动物文件底部有一个空格(我不能简单地删除它)所以当我处理 while 循环,它包括带空格的行。任何帮助都会很棒! 我的文件也如下所示:AnimalName:AnimalType:RegoNumber:ProblemNumber。
while (!infile.eof()) {
getline(infile, ani[i].animalName, ':');
getline(infile, ani[i].animalType, ':');
getline(infile, str, ':');
ani[i].Registration = stoi(str);
getline(infile, str, '.');
ani[i].Problem=stoi(str);
cout << "Animal added: " << ani[i].Registration << " " << ani[i].animalName << endl;
AnimalCount++;
i++;
}
最佳答案
如果该行包含仅一个空格,您能否检查它的长度(应为 1)以及它是否等于一个空格?
如果检测到这样一条线,只需打破循环即可。
#include <iostream>
#include <fstream>
int main(void) {
std::ifstream infile("thefile.txt");
std::string line;
while(std::getline(infile, line)) {
std::cout << "Line length is: " << line.length() << '\n';
if (line.length() == 1 && line[0] == ' ') {
std::cout << "I've detected an empty line!\n";
break;
}
std::cout << "The line says: " << line << '\n';
}
return 0;
}
对于测试文件(第二行包含一个空格):
hello world
end
输出符合预期:
Line length is: 11
The line says: hello world
Line length is: 1
I've detected an empty line!
关于c++ - 如何忽略文件底部的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55529074/