为什么 scanf 会跳过输入?
我对以下程序中 scanf 的行为感到困惑.scanf 似乎输入一次,然后不再输入,直到打印出一个字符流.
I am confused about scanf's behaviour in the following program. scanf appears to input once, and then not input again, until a stream of characters is printed.
下面是一个C程序
#include<stdio.h>
int main()
{
int i, j=0;
do
{
++j;
scanf("%d", &i);
printf("
%d %d
", i, j);
}
while((i!=8) && (j<10));
printf("
J = %d
", j);
return 0;
}
在这里,直到我输入任何整数程序都可以正常工作,但是当输入一个字符时,它会继续打印 i 的最后输入值并且永远不会停止(直到循环退出时 j 为 10)以便 scanf 接受下一个输入.
here, Till i am inputting any integer program works perfectly fine, but when a character is inputted it goes on printing the last inputed value of i and never stops(untill j is 10 when loop exits) for scanf to take next input.
output::
1 <-----1st input
1 1
2 <---- 2nd input
2 2
a <---- character input
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
J = 10
同样的事情也在 C++ 中发生.
same thing is happening in c++ also.
#include<iostream>
using namespace std;
int main()
{
int i, j=0;
do
{
++j;
cin>>i;
cout<<i<<" "<<j<<"
";
}
while((i!=8) && (j<10));
cout<<"
j = "<<j<<"
";
}
output of c++ program ::
1 <-----1st input
1 1
2 <-----2nd input
2 2
a <------ character input
0 3
0 4
0 5
0 6
0 7
0 8
0 9
0 10
j = 10
c++ 中唯一的变化是打印 0 而不是最后一个值.
only change in c++ is that 0 is being printed instead of last value.
我知道这里程序需要整数值,但我想知道当输入字符代替整数时会发生什么?以上所有发生的原因是什么?
I know here integer values are expected by the program, but i want to know what happens when character is inputted in place of an integer? what is the reason of all happening above?
推荐答案
当你输入 a
时,然后 cin >>i
无法读取,因为 i
的类型是 int
无法读取字符.这意味着,a
永远留在流中.
When you enter a
, then cin >> i
fails to read it because the type of i
is int
to which a character cannot be read. That means, a
remains in the stream forever.
现在为什么 i
打印 0
是另一回事.实际上它可以打印任何东西.一旦尝试读取失败,就不会定义 i
的内容.scanf
也会发生类似的事情.
Now why i
prints 0
is a different story. Actually it can print anything. The content of i
is not defined once the attempt to read fails. Similar thing happens with scanf
as well.
正确的写法:
do
{
++j;
if (!(cin>>i))
{
//handle error, maybe you want to break the loop here?
}
cout<<i<<" "<<j<<"
";
}
while((i!=8) && (j<10));
或者简单地这个(如果你想在发生错误时退出循环):
Or simply this (if you want to exit loop if error occurs):
int i = 0, j = 0;
while((i!=8) && (j<10) && ( cin >> i) )
{
++j;
cout<<i<<" "<<j<<"
";
}
相关文章