Character input in scanf(“%d”, &value) [duplicate]

2019-05-27 09:59发布

问题:

This question already has an answer here:

  • What happens if C tries to scan character in integer variable [duplicate] 3 answers

In brief my code is,

#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    while(n != 0)
    {
        scanf("%d", &n);
        printf("%d\n", n);
    }
    return 0;
}

It was written for integer input. But if I input a character instead (although n is decleared as integer), the loop goes infinite and prints the last integer input value. If I input a character at first it seems like it prints a memory address. My question is, what is happening here if I input a character instead an integer?

回答1:

Actually when the other character was inserted it won't taken as a input, it is present in the input buffer, it can't read by the control string.

The %d control string is used to read the character of integer until other characters.

While inserting the other character due to read nothing the loop is continuously running and print the exist value of the variable.



回答2:

When scanf fails, it does not remove the character from input buffer (It does remove data from buffer when it succeeds). So, the next time scanf is triggered in the loop, it will not wait for user input at all (since it has an unread character in its buffer). But it fails again, and again (since everytime it fails) and hence will go into an infinite loop.

I strongly believe the first scanf contains %c as format specifier.
You can get rid of infinite loop by

if(scanf("%d",&n)==0) break;



回答3:

scanf("%d", &n); means only get number data from stdin, such as 1, 2.

So, if you type char in second input, such as 'a', 'b', the input char is not stored in &n. n still has first input number data.

Therefore, infinite loop comes.



标签: c printf scanf