c++ - 如何忽略文件底部的空格?

标签 c++ while-loop ifstream

我有一个包含动物数据的文件,我读取每一行并将信息处理到我的结构数组中,但问题是动物文件底部有一个空格(我不能简单地删除它)所以当我处理 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/

相关文章:

c++ - ifstream 总是返回 "ELF"给对象

c++ - 从 Base 引用对象调用派生类的成员

c++ - STL 迭代器继承 : 'value_type' does not name a type

使用 Boost Thread 的 C++ 链接器错误

c++ - 当我单击Win32 API中的窗口时,如何打开和关闭弹出菜单?

mysql - 在 sp mysql 的 while 循环中插入 select 语句

objective-c - Objective C 中的条件语句到底是什么?

bash - 如何将 grep 重定向到 while 循环

c++ - 在 g++ 和 msvc 中使用 ifstream 读取文件的差异

C++如何将ifstream内容(来自文件)分配给具有偏移量的字符串(istreambuf_iterator)