如何忽略文件底部的空格

How to ignore a space at the bottom of the file?

本文关键字:空格 底部 文件 何忽略      更新时间:2023-10-16

我有一个包含动物数据的文件,我读取每一行并将信息处理到我的结构数组中,但问题是动物文件的底部有一个空格(我不能简单地删除它(,所以当我处理 while 循环时,它包括带有空格的行。任何帮助都会很棒!我的文件也看起来像这样:动物名称:动物类型: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!