简体   繁体   English

当我告诉她只读取第一个字符时,scanf 读取了整个字符串

[英]Scanf reading an entire string when I told her to only read the first character

#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:我告诉 scanf:“读取用户给你的第一个字符”,她说“是的,主人”,但如果我输入字符串“aaaaaaaaaaaaaaaaaa”,我得到 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.它是一个。它是一个。它是一个。它是一个。它是一个。它是一个。它是一个。它是一个。它是一个。它是一个。它是一个。它是a. 这是一个。

Doesn't the %1c mean it throws away the rest of the string? %1c 不是意味着它会丢弃字符串的 rest 吗? As a bonus point, after I get that long output, I keep inputing a and it does nothing.作为奖励,在我得到那么长的 output 之后,我一直输入 a 但它什么也没做。 What in the god damn is wrong with this cursed command?这个该死的命令到底有什么问题?

In this while loop when a sequence of characters like this "aaaaaaaaaaaaaaaaaaa" is typed在此 while 循环中,当键入诸如"aaaaaaaaaaaaaaaaaaa"之类的字符序列时

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.在循环的第一次迭代中,第一次调用scanf读取输入字符串的第一个字符'a' 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.然后调用getchar会跳过输入字符串的第二个字符'a' ,然后在循环的下一次迭代中,第一次调用scanf会读取输入字符串的第三个字符'a' ,依此类推。

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.");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM