C++ Primer第三章例题

opposever 2008-04-06 08:01:06
#include <iostream>
#include <string>
using std::cin;
using std::endl;
using std::string;
int main()
{
string word;
while(cin>>word)
cout<<word<<endl;
return 0;
}
这里说没有到达文件尾或无效输入,则执行while循环体,它是怎么判断有没有到达文件尾的?一个文件长度有限制吗?
...全文
88 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZiSheng 2008-04-07
  • 打赏
  • 举报
回复
cin是一个istream对象,既然是对象当cin<<word的时候就会调用自己的成员函数
既然是调用函数那么他就会有一个返回值,这个返回值就应该是判断是否结束的标志
hellodudu 2008-04-06
  • 打赏
  • 举报
回复
cmd里面ctrl+z就是结束了
lunarfan 2008-04-06
  • 打赏
  • 举报
回复
EOF
opposever 2008-04-06
  • 打赏
  • 举报
回复
呵呵 谢谢大家,或许是我钻牛角尖了^_^
effective_person 2008-04-06
  • 打赏
  • 举报
回复
在这里不是什么文件,而是stream
至于文件的结尾在那里?
我个人是这样理解的。
以上面的为例:
while (cin >> word) {
cout << word << endl;
}
这cin>> word;
每次输入一个int, 就在缓冲区加一个int 。把这样的一组int看作输入流。当你ctrl +Z后就有流的尾了。

----其实这个问题很难解答!你说cin为什么可以像 bool一样看待呢?怎么就单独cin就可以判定。
我看很多书上都没有说清楚。
说不清楚。(至少我看的书上没有)
本人才疏学浅!
不要见笑哦o(∩_∩)o...哈哈
opposever 2008-04-06
  • 打赏
  • 举报
回复
eofbit, to record end-of-file while extracting from a stream
在文件结尾标记,是这个不?在CMD里输入的,文件在哪里?结尾又在哪里?
Inhibitory 2008-04-06
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using std::cin;
using std::endl;
using std::string;
int main()
{
string word;
while(cin>>word) // cin >> word输入后返回的是一个std::istream对象,这里即cin,当cin的状态是有效的时候,可以继续输入,当cin的状态是无效的时候,while 循环退出.用string来测试不太好.
// 如果用输入int值来测试的话,就很容易了,当输入的不是int值,而是一个字母等,这时cin的状态就会改成不可继续输入状态,while循环退出.
cout < <word < <endl;
return 0;
}
这里说没有到达文件尾或无效输入,则执行while循环体,它是怎么判断有没有到达文件尾的?一个文件长度有限制吗?

这个程序与文件没有关系,只是在进行读取文件内容时,当读到文件尾时,ifstream的状态被改变为不可继续输入状态,即读完文件了.

#include  <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main() {
int word;
while (cin >> word) {
cout << word << endl;
}

return 0;
}


effective_person 2008-04-06
  • 打赏
  • 举报
回复
没有到达文件尾或无效输入
----?难道无效输入也可以循环?
应该是没有遇到文件尾部和无效输入。

msdn 中输入流状态的判断如下,文件肯定是有限长的啦!

/*
ios_base::iostate
typedef T2 iostate;
static const iostate badbit, eofbit, failbit, goodbit;
The type is an enumerated type T2 that describes an object that can store stream state information. The distinct flag values are:

badbit, to record a loss of integrity of the stream buffer
eofbit, to record end-of-file while extracting from a stream
failbit, to record a failure to extract a valid field from a stream
In addition, a useful value is:

goodbit, no bits
*/

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧