-1
#include <stdio.h>

int main(){
    
    while(1){

        char a;
        scanf("%1c",&a);
        getchar();
        if (a=='a'){
            printf("It is a.");
        }

    }
    
}

I told scanf: "Read the first character of whatever the user gives you", and she said "yes master", but if I input the string "aaaaaaaaaaaaaaaaaaa" i get the output:

It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.It is a.

Doesn't the %1c mean it throws away the rest of the string? As a bonus point, after I get that long output, I keep inputing a and it does nothing. What in the god damn is wrong with this cursed command?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • No, `%1c` does not mean to throw away the rest of the string. – Steve Summit Nov 23 '22 at 19:52
  • Don't try to use `scanf` to read individual characters. That's not what it's for. Use it to easily read single integers, or single floating-point numbers, or maybe simple strings (not containing whitespace). Anything else tends to be more trouble than it's worth. See also [these guidelines](https://stackoverflow.com/questions/72178518#72178652). – Steve Summit Nov 23 '22 at 19:55

1 Answers1

0

In this while loop when a sequence of characters like this "aaaaaaaaaaaaaaaaaaa" is typed

while(1){

    char a;
    scanf("%1c",&a);
    getchar();
    if (a=='a'){
        printf("It is a.");
    }

}

in the first iteration of the loop the first call of scanf reads the first character 'a' of the entered string. Then the call of getchar skips the second character 'a' of the entered string and then in the next iteration of the loop the first call of scanf reads the third character 'a' of the entered string and so on.

That is the input buffer still keeps the entered string until it will be entirely read.

It seems what you need is the following

while(1){
    char a;
    scanf(" %c",&a);
    while ( getchar() != '\n' );
    if (a=='a'){
        printf("It is a.");
    }
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335