[问题] 程式出现了预期之外的输出

楼主: jack41402 (抹茶好喝)   2020-03-12 20:40:40
问题(Question):
用cin.eof()时遇到错误,输入时遇到EOF应该终止程式而不继续运行,但程式却多输出一次,想知道为什么会有错误?
喂入的资料(Input):
0 0 5 10 0 8
0 0 5 10 10 5
预期的正确结果(Expected Output):
Quick in
Nearly
错误结果(Wrong Output):
Quick in
Nearly
Nearly
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
double x1 , x2 , y1 , y2 , r1 , r2 , temp ;
while (!cin.eof())
{
cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2 ;
temp = sqrt (pow (x1 - x2 , 2) + pow (y1 - y2 , 2));
if ((r1 + r2)>=temp)
{
cout << "Quick in" << endl ;
}
else if ((r1 + r2) < temp)
{
cout << "Nearly" << endl ;
}
}
}
http://codepad.org/tnRLqQJK
补充说明(Supplement):
这个程式是在写下面这题
https://toj.tfcis.org/oj/pro/19/
作者: Schottky (顺风相送)   2020-03-12 21:03:00
你确定最后多出来那一轮的 cin 有收到资料吗?
作者: Lipraxde (Lipraxde)   2020-03-12 21:04:00
我记得这个 eof() 是在读到 EOF 后才会返回 true,是用来判断上次读取的状态用的把那个长长的 com >> ... 当成 while 的 condition 应该就够了进循环后就是 >> r2 的那次http://www.cplusplus.com/reference/ios/ios/eof/ 你看文件好了 "Return Value",我中文没有表达的很清楚QQ
作者: LPH66 (-6.2598534e+18f)   2020-03-13 00:24:00
重点在于 cin.fail() 等判断方式都是“上一次是否错误”并没有“等一下还有没有东西”这回事--要知道等一下有没有东西就真的要等一下看了之后才知道这一点就连大家说的 while(cin >> ...) 这个判断也不例外只不过这是在读完后马上判断它有没有失败而已

Links booklink

Contact Us: admin [ a t ] ucptt.com