Take the 2-minute tour ×

I am learning C and have some questions. I know my questions may be a common question but I could not find the answer. I have the following program:

int main(int argc, char *argv[])
  int a, b;
  char c1, c2;
  printf("Enter something: ");
  scanf("%d",&a); // line 1
  printf("Enter other something: ");
  scanf("%d", &b); // line 2

  printf("Enter a char: "); 
  scanf("%d",&c1); // line 3
  printf("Enter other char: ");
  scanf("%d", &c2); // line 4

  printf("Done"); // line 5


  return 0;

As I read in the C book, the author say that scanf() left a new line character in the buffer, therefore, the program does not stop at line 4 for user to enter the data, rather it stores the new line character in c2 and moves to line 5. Is that right? However, I was wondering this only happen with char data types? Because I did not see this problem with int data types as in line 1, 2, 3. It is right?


share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

The scanf function removes whitespace automatically before trying to parse things other than characters. The character formats (primarily %c) are the exception; they don't remove whitespace.

share|improve this answer
add comment

use scanf("\n%d", &c2); This will solve your problem.

share|improve this answer
This should be the correct <b>answer</b>. –  oasisweng Jan 17 at 9:11
add comment

Your Answer


