A + B Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 376937 Accepted Submission(s): 119082
#include<iostream> #include<cstdio> #include<windows.h> using namespace std; int main() { int x,a,b; freopen("cin.txt","r",stdin); int T=7; while(T--) { cout<<(cin>>a)<<endl; system("pause"); } }
其中cin.txt如下:
1 2 3 4 5
在codeblock下的运行结果:

把程序改成如下:
#include<iostream> #include<cstdio> #include<windows.h> using namespace std; int main() { int x,a,b; freopen("cin.txt","r",stdin); int T=3; while(T--) { cout<<(scanf("%d",&a))<<endl; cout<<(scanf("%d%d",&a,&b))<<endl; system("pause"); } }
cin.txt文件不变,结果如下
可见cin的返回值可能是其地址或神马的,当无输入时,返回0;
而scanf返回的是成功读到的变量的数量
while(cin>>a>>b)
这样当结束时,无输入,所以cin>>a>>b的返回值为0,结束循环。
用C可以这样:
while(~scanf("%d%d",&a,&b))
这样,当结束是返回值为-1,取~后为0;
也可以
while(scanf("%d%d",&a,&b)!=EOF)
因为EOF=-1;
当然根据上述内容,scanf可以灵活运用。
言归正传,还是给出Hdu1000这道报到题AC的代码,算是作为开门第一篇的结束:
#include<iostream> using namespace std; int main() { int a,b; while(cin>>a>>b) cout<<a+b<<endl; }
原文:http://www.cnblogs.com/shumabaobei/p/hdu_1000.html