cin.eof() 的值代表什么C++?
What's the C++ cin.eof()'s value represent?
在 istream 中,我使用 cin.getline((
接受一些字符,然后输入 EOF 信号(因为我的操作系统是 MAC,我按 control + D(,然后是第二个 cin.getline(( 来接受流的其余部分。但是,我在第一个cin.getline((之前测试了cin.eof((的值3次,在第一个和第二个cin.getline((之间,最后。在这个程序中,我都使用 EOF 信号来终止这三个 cin.getline((;
代码:
#include<iostream>
using namespace std;
int main()
{
cout<<"now EOF:"<<cin.eof()<<endl;
char character[10];
cout<<"input ten digit character,with '!' in the middle,end with EOF(ctrl+d):"<<endl;
cin.getline(character, 10,'!');
cout<<endl;
cout<<"get the character:"<<endl;
cout<<character<<endl;
char character2[10];
cout<<"now EOF:"<<cin.eof()<<endl;
cout<<"press(ctrl+d):"<<endl;
cin.getline(character2, 10,'!');
//cin>>character2;
cout<<endl;
cout<<character2<<endl;
cout<<"now EOF:"<<cin.eof()<<endl;
}
结果在这里:
now EOF:0
input ten digit character,with '!' in the middle,end with EOF(ctrl+d):
123!456
get the character:
123
now EOF:0
press(ctrl+d):
456
now EOF:1
但是当我用注释的部分 cin>>字符 2 替换 cin.getline(字符 2, 10,'!'( 时:
结果是:
now EOF:0
input ten digit character,with '!' in the middle,end with EOF(ctrl+d):
123!456
get the character:
123
now EOF:0
press(ctrl+d):
456
now EOF:0
我想知道为什么会发生这种情况以及 cin.eof(( 值如何变化。谢谢!
在第二个示例中,换行符仍可供读取 - 您已经读取了一个字符串,而不是一行。
看到输出中缺少的额外换行符了吗?这就是线索。
但更重要的是,不要使用eof
。请参阅为什么"while ( !feof (file(("总是错误的?
如果istream::eof()
返回true
则表示上一个输入操作失败,因为流位于文件末尾。这就是为什么你不能用它来控制输入循环:当它为真时,输入已经失败了。这就是为什么输入操作本身可以告诉你它们是否成功:这样,只要输入成功,你就可以循环。此代码
while (cin.getline(whatever)) {
do_something(whatever);
}
将在每次getline
调用读取一行时执行循环。当cin
到达输入末尾时,getline
调用将失败,并且不会执行循环。此代码:
while (!cin.eof()) {
cin.getline(whatever);
do_something(whatever);
}
将调用do_something
,即使对getline
的调用失败。调用失败后,下次通过循环时,cin.eof()
将返回 true,循环将退出。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 我应该使用什么来代替void作为变体中的替代类型之一
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用