关于c的小疑点
关于c的小问题
下面的程序,是正确的!当我出入两个整数时,可得到正确的答案,但是当我输入两个字母时,就出现了死循环,有两个问题:
1:如何修改在出入两个整数时正确,但输入一个以上的字母时报错,但不出现死循环?
2:Turbo c&C++出现死循环时如何停止?
#include <stdio.h>
int main()
{
int a,b;
while(scanf("%d %d",&a, &b) != EOF)
printf("%d\n",a+b);
}
------解决方案--------------------
关于scanf的返回值,MSDN里是这样写的:
Both scanf and wscanf return the number of fields successfully converted
and assigned; the return value does not include fields that were read but
not assigned. A return value of 0 indicates that no fields were assigned.
The return value is EOF for an error or if the end-of-file character or the
end-of-string character is nocountered in the first attempt to read a character.
如:
scanf("%d%d", &a, &b);其返回值是成功读入数据的个数;
如果a和b都被成功读入,那么scanf的返回值就是2
如果只有a被成功读入,返回值为1
如果a和b都未被成功读入,返回值为0
如果遇到错误或遇到end of file,返回值为EOF。
&是一个寻址符,如果输入字符程序会去找内存中的地址,然后去读他的值,所以scanf是读不到的,返回值也不会为EOF!
为防止其进入死循环可加入一条语句:getchar();
下面的程序,是正确的!当我出入两个整数时,可得到正确的答案,但是当我输入两个字母时,就出现了死循环,有两个问题:
1:如何修改在出入两个整数时正确,但输入一个以上的字母时报错,但不出现死循环?
2:Turbo c&C++出现死循环时如何停止?
#include <stdio.h>
int main()
{
int a,b;
while(scanf("%d %d",&a, &b) != EOF)
printf("%d\n",a+b);
}
------解决方案--------------------
关于scanf的返回值,MSDN里是这样写的:
Both scanf and wscanf return the number of fields successfully converted
and assigned; the return value does not include fields that were read but
not assigned. A return value of 0 indicates that no fields were assigned.
The return value is EOF for an error or if the end-of-file character or the
end-of-string character is nocountered in the first attempt to read a character.
如:
scanf("%d%d", &a, &b);其返回值是成功读入数据的个数;
如果a和b都被成功读入,那么scanf的返回值就是2
如果只有a被成功读入,返回值为1
如果a和b都未被成功读入,返回值为0
如果遇到错误或遇到end of file,返回值为EOF。
&是一个寻址符,如果输入字符程序会去找内存中的地址,然后去读他的值,所以scanf是读不到的,返回值也不会为EOF!
为防止其进入死循环可加入一条语句:getchar();
- C/C++ code
#include <stdio.h> int main() { int a,b; while(scanf("%d %d",&a,&b) != EOF) { printf("%d\n",a+b); getchar();//********// } }
------解决方案--------------------
如果你想提示错误并退出死循环,可以修改成如下:
- C/C++ code
#include <stdio.h> int main() { int a,b; while(1) { if(scanf("%d %d",&((int)a),&((int)b) )==0) { printf("error!");//如果未成功读入则提示错误 break; } printf("%d\n",a+b); } return 0; }