提示时C无限循环问题
为什么在这段代码中,它在不再次提示用户的情况下执行无限循环提示时C无限循环问题,c,infinite-loop,scanf,rot13,C,Infinite Loop,Scanf,Rot13,为什么在这段代码中,它在不再次提示用户的情况下执行无限循环 #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){ prin
#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;}
}
}
#包括
#包括
#包括
无效至_rot13(字符*值);
int main(){
字符字[1024];
printf(“C ROT13\n要编码或解码的某些数据”);
而(1){
printf(“:”);
scanf(“%[^\n]s”,字);
至第13页(文字和文字);
printf(“:%s\n”,word);
}
返回0;
}
void to_rot13(字符*值){
无符号整数x;
对于(x=0;值[x]!='\0';x++){
如果((值[x]<'A')||(值[x]>'Z'&&x]<'A')|(值[x]>'Z')){}
否则如果(tolower(value[x])您正在将&word发送到到\u rot13
(您应该发送word或&word[0])您正在将&word发送到到\u rot13
(您应该发送word或&word[0])
将换行保留在输入缓冲区中,因此下一个scanf
将立即返回,而不读取任何进一步的输入,因为缓冲区中的第一个char
是换行符。您需要从输入缓冲区中删除换行符
int c;
do {
c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
exit(EXIT_FAILURE); // input borked
}
此外,请注意编译器的警告,并将word
而不是&word
传递到到\u rot13
将换行保留在输入缓冲区中,因此下一个scanf
将立即返回,而不读取任何进一步的输入,因为缓冲区中的第一个char
是换行符。您需要从输入缓冲区中删除换行符
int c;
do {
c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
exit(EXIT_FAILURE); // input borked
}
此外,请注意编译器的警告,将word
而不是&word
传递到到\u rot13
是否将其保留在缓冲区中以供下次只读(因此您只会得到一次重复,而不是无限次重复)?否下一个scanf
再次读取,直到它找到一个新行,并将其保留在缓冲区中。它是否只将其保留在缓冲区中以供下一个只读(因此您只能获得一次重复,而不是无限次重复)?否下一个scanf
再次读取,直到它找到一个新行,并将其保留在缓冲区中。