gpt4 book ai didi

提示时出现 C 无限循环问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:37:24 24 4
gpt4 key购买 nike

为什么在这段代码中它会在不再次提示用户的情况下进行无限循环

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void to_rot13(char* value);

int main(){
char word[1024];
printf("C ROT13\nSome data to code or decode\n");
while (1){
printf(": ");
scanf("%[^\n]s", word);
to_rot13(&word);
printf(": %s\n", word);
}
return 0;
}


void to_rot13(char* value){
unsigned int x;
for (x = 0; value[x] != '\0'; x++){
if ((value[x] < 'A') || (value[x] > 'Z' && value[x] < 'a') || (value[x] > 'z')){}
else if (tolower(value[x]) <= 'm'){value[x] = value[x] + 13;}
else{value[x] = value[x] - 13;}
}
}

我想再次提示用户我再精确不过了。

最佳答案

scanf("%[^\n]s", word);

将换行符留在输入缓冲区中,因此下一个 scanf 会立即返回而不读取任何进一步的输入,因为缓冲区中留下的第一个 char 是一个换行符。您需要从输入缓冲区中删除换行符。

int c;
do {
c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
exit(EXIT_FAILURE); // input borked
}

此外,注意编译器的警告,将 word 而不是 &word 传递给 to_rot13

关于提示时出现 C 无限循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13184588/

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