Symbol Input.

Tell me if I did anything wrong with this. I can input j, i, a. And after I input b, my program just skip the third scanf and do printf.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>

main(){
  unsigned int x, y;
  char a, b;
  int i, j;
  
  scanf("%d %d", &j, &i);
  scanf("%c %c", &a, &b);
  scanf("%d %d", &x, &y);
  
  printf("First line(random number): %d %d\n", j, i);
  printf("Second line(symbol): %c %c\n", a, b);
  printf("Last line(unsiged integer): %d %d\n", x, y);
}


My input:
3 6
* _


output:
First line(random number): 3 6
Second line(symbol):
 *
Last line(unsigned integer): 20 8
Last edited on
The problem is that %c does not skip whitespace characters. When you enter the data the way you have done a will get the newline character between 6 and *.

If you write the input without anything between 6 and * you'll see that it works.
3 6* _ 13 16

To consume all whitespaces before reading the character you can add a space before %c.
1
2
scanf(" %c %c", &a, &b);
       ^
Last edited on
So you mean that the first %c reads a newline character(\n), right? Then b reads *. That's why when reading x which is a %d but I input a symbol(_), it stops right away!! Got it!! Tks~
Yeah, that's right.
Topic archived. No new replies allowed.