为什么scanf函数出现跳过输入? [英] Why does scanf appear to skip input?

查看:251
本文介绍了为什么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("\n\n%d %d\n\n", i, j);
    }
    while((i!=8) && (j<10));  

    printf("\nJ = %d\n", j);
    return 0;
}

在这里,直到我正在输入的任意整数程序工作完全正常,但是当一个字符被输入那张打印我的最后一个inputed价值和永不停止(直到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<<"\n";
    }
    while((i!=8) && (j<10));

    cout<<"\nj = "<<j<<"\n";
}   


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&GT;&GT;我无法读取它,因为类型 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 是一个不同的故事。实际上,它可以打印任何东西。 的内容我没有定义一次读取尝试失败。类似的事情发生与 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<<"\n";
}
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<<"\n";
}

这篇关于为什么scanf函数出现跳过输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆