Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why to put space between %d and %c while inputting there values using scanf

Tags:

c

im a beginner to C,, and i was writing a code to print a square of a user entered character.

usually when we need to input two integers (say x and y) using scanf() we write this scanf("%d%d", &x, &y) but according to the needs of my code i am supposed to input one integer (say m) and a character (say ch).

I wrote it as scanf("%d%c", &x, &ch) but it has an error, when i execute the program it only asks the integral value to be entered and then it just stop executing.

I searched for this and i found that i need to put space between %d and %c as scanf("%d %c", &x, &ch);

Can anyone explain this why we need to put space between this?

like image 265
pranav Avatar asked Aug 22 '14 02:08

pranav


1 Answers

Meaning of whitespace characters in the format string (from http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf):

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

When your code is:

scanf("%d%c", &x, &ch)

and you enter

10

in your console:

  1. 10 is read and stored in x.
  2. the newline character is read and stored in ch.

If you use

scanf("%d %c", &x, &ch)

and you enter

10
  1. 10 is read and stored in x.
  2. the newline character and other whitespace characters are consumed. The program waits for a non-whitespace character. Once a line of input is entered and at least one non-whitespace character is present in the line, the first non-white character of the line is read into ch. This is because stdin is typically line buffered.
like image 199
R Sahu Avatar answered Sep 28 '22 05:09

R Sahu