cin 忽略 eof 字符? !!!并返回被忽略的 eof 字符的 -0 值
这是我的递归程序,它反转 eof 之前输入的数字,但当找到 eof 字符 ^Z 时它不会停止。直到我按 Enter 并在新行中写入 eof 字符。
示例图片: http://www.imageupload.org/?d=F9D743081
#include <iostream>
using namespace std;
void recursive()
{
long double n;
if((cin>>n))
recursive();
cout<<n<<endl;
}
int main()
{
recursive();
return 0;
}
什么是错误的?
Here is my recursive program which reverses numbers entered before eof, but it does not stop when eof character ^Z is found. Until I press enter and write eof character in new line.
example image: http://www.imageupload.org/?d=F9D743081
#include <iostream>
using namespace std;
void recursive()
{
long double n;
if((cin>>n))
recursive();
cout<<n<<endl;
}
int main()
{
recursive();
return 0;
}
What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该将代码编写为:
现在它仅打印成功读取的值。你的程序也会打印出读取失败的信息;最后一次读取不成功,但您的
cout
仍然尝试打印n
。顺便说一句,您不需要按
^Z
来停止递归。您可以按一些字母或一些其他非数字字符来停止递归。演示:http://www.ideone.com/D4XT1
You should be writing your code as:
It now prints only the successfully read values. Your program would print unsuccessful read as well; the last read is unsuccessful, but your
cout
attempts to printn
anyway.By the way, you don't need to press
^Z
to stop the recursion. You can press some alphabets or some other non-digit characters, to stop the recursion.Demo : http://www.ideone.com/D4XT1