在C语言中,为什么有时只需要getchar()来删除字符?

在C语言中,为什么有时只需要getchar()来删除字符?,c,if-statement,getchar,C,If Statement,Getchar,我正在尝试使用getchar从输入缓冲区中删除字符。在下面的代码中,要求用户输入一个要选择的选项,然后根据该选项,需要另一个输入,类型为int或char string 在int情况下,不需要getcar,scanf正确地接收输入。但是在char的情况下,scanf在没有事先使用getchar的情况下无法获取输入。这有什么原因吗 printf("Available Ciphers:\n1) Caesar Cipher\n2) Vigenere Cipher\nSelected Cipher: ")

我正在尝试使用getchar从输入缓冲区中删除字符。在下面的代码中,要求用户输入一个要选择的选项,然后根据该选项,需要另一个输入,类型为int或char string

在int情况下,不需要getcar,scanf正确地接收输入。但是在char的情况下,scanf在没有事先使用getchar的情况下无法获取输入。这有什么原因吗

printf("Available Ciphers:\n1) Caesar Cipher\n2) Vigenere Cipher\nSelected Cipher: ");
if(scanf("%d", &choice) != 1){
    printf("Error: Bad selection!\n");
    exit(EXIT_SUCCESS);
} else if (choice != 1 && choice != 2){
    printf("Error: Bad Selection!\n");
    exit(EXIT_SUCCESS);
//If the choice entered is correct, then run the following.
} else {
    if(choice == 1){
        printf("Input key as nuumber: ");
        if(scanf("%d", &caesarkey) != 1){ //Why is getchar() not needed here?
            printf("Error: Bad Key!\n");
            exit(EXIT_SUCCESS);
        }
        //morecode here
    } else if (choice == 2){
        printf("Input key as string: ");
        while(getchar() != '\n');  //Why is this needed here?
        /*Uses scanf and not fgets, since we do not want the
        key to contain the newline character '\n'. This is
        due to the fact that the newline character is not
        considered in the function that encrypts and decrypts
        plaintext and ciphertext.*/
        if(scanf("%[^\n]s", vigencipherkey) != 1){
            printf("Error, Cannot read inputted key!\n");
            exit(EXIT_SUCCESS);
        }
        //More code here..
    }
}

要读取用户输入的行的其余部分,可以使用以下功能:

int flush_line(void) {
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        continue;
    return c;
}
注:

c必须定义为int,以容纳unsigned char类型的所有值和特殊负值EOF。 您应该测试“\n”和EOF,否则您将在文件的过早结束时有一个无尾随换行符的无休止循环,例如,如果您从空文件重定向程序的输入,就会发生这种情况。 您可以通过比较flush_行的返回值和EOF来测试文件的结尾。
看起来您是在扫描字符串而不是int,因此,您传递的是int而不是int的地址

换行

   if(scanf("%[^\n]s", vigencipherkey) != 1){


我试过了,它允许我输入一些东西,但不管怎样,我都会收到错误消息错误,无法读取输入的密钥!你真的想要最后的扫描格式吗?无论如何,最好使用fgets读取一行。@Shawn我一开始是这样做的,但我在另一个文件中编写的函数没有考虑“\n”字符,这就是我使用scanf的原因。@xing谢谢你的回答,我不知道scanf在缓冲区中留下了一个换行字符。谢谢你澄清这一点^^如果不需要,只需从字符串中删除换行符即可。
  if (scanf("%d", &vigencipherkey) != 1) {