c++使用eof()读取未定义的行数
c++ reading undefined number of lines with eof()
我正在使用eof((处理一个问题。使用
string name;
int number, n=0;
while(!in.eof())
{
in >> name >> number;
//part of code that puts into object array
n++;
}
对我来说,这听起来很正常,因为每当文件中没有更多文本时。但我得到的是4200317。当我查看数组条目时,我会看到第一个是文件中的,另一个是0。
可能是什么问题?我应该如何解决?也许有一种替代读取问题的方法(具有未定义的行数(
正确的方法:
string name;
int number;
int n = 0;
while(in >> name >> number)
{
// The loop will only be entered if the name and number are correctly
// read from the input stream. If either fail then the state of the
// stream is set to bad and then the while loop will not be entered.
// This works because the result of the >> operator is the std::istream
// When an istream is used in a boolean context its is converted into
// a type that can be used in a boolean context using the isgood() to
// check its state. If the state is good it will be converted to an objet
// that can be considered to be true.
//part of code that puts into object array
n++;
}
为什么你的代码失败:
string name;
int number, n=0;
while(!in.eof())
{
// If you are on the last line of the file.
// This will read the last line. BUT it will not read past
// the end of file. So it will read the last line leaving no
// more data but it will NOT set the EOF flag.
// Thus it will reenter the loop one last time
// This last time it will fail to read any data and set the EOF flag
// But you are now in the loop so it will still processes all the
// commands that happen after this.
in >> name >> number;
// To prevent anything bad.
// You must check the state of the stream after using it:
if (!in)
{
break; // or fix as appropriate.
}
// Only do work if the read worked correctly.
n++;
}
in << name << number;
这看起来像是写作,而不是阅读。我错了吗?
int number, n = 0;
您没有初始化n
,而且您似乎有拼写错误。
这可能是更正确的
string name;
int number, n = 0;
while (in >> name && in >> number)
{
n++;
}
eof是一种糟糕的做法。
请注意,这里与您的代码有一个细微的区别:您的代码在遇到eof
时结束,或者如果发现错误的行(例如Hello World
(,则无提示循环无限长时间,当遇到名称+编号格式不正确的"元组"或文件结束时(或者存在其他错误,如在操作过程中断开磁盘连接:-(,此代码结束。如果要检查文件是否正确读取,则在while
之后,可以检查in.eof()
是否为true。如果这是真的,那么所有文件都被正确读取了。
相关文章:
- 编译C++时未定义的引用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 如何使用数组 (C++) 读取具有未定义数量的值的 .txt 文件?
- 从文件行读取未定义数量的变量
- 如何读取NM命令:NM选项-T和-U(未定义)是什么意思
- 未定义的行为怪癖:在缓冲区外读取导致循环永远不会终止
- 读取文件内容时未定义的字符,文件末尾没有换行符
- 如何从uint8_t的缓冲区读取带符号整数,而不调用未定义或实现定义的行为
- 组合框初始化错误:无法读取未定义的属性'constructor'
- 如何使用 boost 从 com 端口读取未定义的字节数
- 使用 iostream 读取和签名字符时未定义的行为
- 读取不是最近在 GCC 中编写的成员是未定义的行为吗?
- c++使用eof()读取未定义的行数
- 从文件中读取对象时未定义的符号
- 通过无符号整数读取无符号字符数组未定义,因此不安全