gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:40:42 24 4
gpt4 key购买 nike

我正在尝试使用getchar()从输入缓冲区中删除字符。在下面的代码中,要求用户输入一个选项进行选择,然后根据选择,需要另一个输入,可以键入 int 或键入 char(字符串)。

int 情况下,不需要 getcar() 并且 scanf 可以正确接收输入。但在 char 情况下,如果不事先使用 getchar()scanf 就无法获取输入。这是有原因的吗?

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,因此,您传递的是 int 而不是 int 的地址。

更改此行

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

  if (scanf("%d", &vigencipherkey) != 1) {

关于c - 在C中,为什么有时只需要getchar()来删除字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55408943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com