如何忽略文件底部的空格
How to ignore a space at the bottom of the file?
我有一个包含动物数据的文件,我读取每一行并将信息处理到我的结构数组中,但问题是动物文件的底部有一个空格(我不能简单地删除它(,所以当我处理 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!
相关文章:
- 2D数组来自文本输入,中间有空格
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- C++为一串单词添加空格
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 如何打印不带空格的输入整数?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 如何忽略文件底部的空格