【问题标题】:How to ignore a space at the bottom of the file?如何忽略文件底部的空格?
【发布时间】:2019-04-05 06:00:05
【问题描述】:

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

【问题讨论】:

  • 请展示带有和不带有问题结尾的文件内容示例。
  • 如果不能保证这些行符合预期的语法,你应该阅读 line be line 并显式解析。
  • 先看this

标签: c++ while-loop ifstream


【解决方案1】:

如果该行包含一个空格,您能否检查它的长度(应该为 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!

【讨论】:

  • 欢迎来到这里。您可以考虑根据 OP 代码编写一个小代码示例来说明您的答案。
猜你喜欢
  • 2015-03-31
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多