0

when I write a for loop to scanf some int value, the output is correct. however, I try to this loop to scanf some char value, it seems something wrong.(I was wondering the space or '\t' as a char to be scanned)

//when the input are
2
1 2
3 4
//
#include<stdio.h>
int main(void){
    int n;
    scanf("%d", &n);
    int x;
    int y;
    for(int i = 0; i< n; i++){
        scanf("%d %d", &x, &y);
    }
    return 0;
}
//when I enter
2
a b
the program is finished and i cannot enter more char.
//
#include<stdio.h>
int main(void){
    int n;
    scanf("%d", &n);
    char x;
    char y;
    for(int i = 0; i< n; i++){
        scanf("%c %c", &x, &y);
    }
    return 0;
}
pipi
  • 53
  • 3
  • 1
    How do you know it's wrong? You don't do anything with these values after reading them. Please specify your input, your expected "output" (effect? maybe you're looking at the values in a debugger?), and your actual output. – JohnFilleau Mar 30 '22 at 19:11
  • 1
    The typical question like this is because: [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) and with `%c` there is no automatic filtering of whitespace. – Weather Vane Mar 30 '22 at 19:14
  • Maybe you want `scanf(" %c %c"` to skip whitespace before each char. – stark Mar 30 '22 at 19:25

1 Answers1

0

Remember, the space (' ') is also a char, so the scanf is reading the space instead of the second letter.

aleiis
  • 1