0

I used scanf("%d" ,&a), but for sake of curiosity I entered alphabets in the input console and to my surprise every time output was 39, why is it so?

I'm a newbie in language, so I made this program which reads/scans the input from the user and prints the output(sort of copy paste program) to get comfortable I used an integer as my variable value, but while executing the code, instead of entering integer I put letters [ex:- 'a', 'aaaaaaa', 'afadfad', 'awsw121', 'a1'] but every time the output was 39.

int a;
 printf("what`s your age in years?\n");

 scanf("%d" ,&a); 

 printf("your age is %d \n" , a);

whenever I put an input like ['1a' , '2afasfadfa' , '5awwee']

{ all input starting with an integer}

the answer comes out to be correct. I think that the code only reads the integer and as soon as it gets its input, It breaks the execution there itself.

melpomene
  • 84,125
  • 8
  • 85
  • 148

2 Answers2

4

When you have %d in scanf and you type a character, the scanf does not read anything. It actually returns a value of 0 elements read.

The value of 39 that you are getting is probably because you have declared int a on the stack and this will have any random value. Running the program again may or may not change this memory.

You can check this by initializing a with some other value e.g. int a = 5 and the output will always be 5.

Also you should always check the return value of scanf to see if you have actually read what you expect.

int a;
printf("what`s your age in years?\n");
if (scanf("%d" ,&a) != 1)
{
   // handle error
}   
printf("your age is %d \n" , a);

I think that the code only reads the integer and as soon as it gets its input, It breaks the execution there itself.

This is not entirely correct. scanf with %d will read the integer and the rest of the characters will remain in the buffer.

So, if you try another scanf with %d it will fail again.

Solution for this scenario is to read the buffer completely and then discard it. e.g. with

int c;
... 
while ((c = getchar()) != '\n' && c != EOF);
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • `while (scanf("%c",&dummy)==1);` will stop only on `EOF`. You probably want `int c; while ((c = getchar()) != '\n' && c != EOF);` – Spikatrix Jul 12 '19 at 06:20
0

scanf() returns the number of successful conversions. If the user types a number, it is converted and stored into variable and scanf() returns 1, if the user enters something that is not a number, such as AA, scanf() leaves the offending input in the standard input buffer and returns 0, finally if the end of file is reached (the user types ^Z enter in windows or ^D in unix), scanf() returns EOF

Shivani Sonagara
  • 1,299
  • 9
  • 21