C循环打印字符串两次? (使用scanf(“%c”))

抱歉可能是愚蠢的问题,但我想练习循环并提出这个想法。基本上它要求你进入或不进入循环,当你进入时,它会要求你做点什么。问题就在我进入循环之后,它打印两次printf字符串,然后传递给scanf并等待输入。 我无法弄明白。 欢迎大家帮忙! 这是代码:

#include  int main() { char check = 'a'; char int_check = 'a'; int b = 0; printf("want to go in? [y or n]\n"); scanf("%c",&check); if ( check == 'y') { while (1){ printf("Waiting: \n"); scanf("%c",&int_check); if ( int_check == 'q'){ printf("You're out, bye!\n"); break; }; }; } else if ( check == 'n'){ printf("You're not in, see ya!\n"); }else { printf("Please, type 'y' or 'n'\n"); }; return 0; } 

如果您在终端上输入以下内容:

 x 

第一个循环将看到一个x

第二个循环将看到换行符。

解决这个问题最简单的方法是使用sscanf和getline。

可以更改程序以立即响应键盘,即无需等待用户按Enter键。 它需要改变输入终端​​的属性,并且通常比面向行的输入更麻烦且更不便携。 此页面描述了如何执行此操作,以下是修改为以这种方式工作的代码:

 #include  #include  #include  #include  struct termios saved_settings; void reset_term_mode(void) { tcsetattr (STDIN_FILENO, TCSANOW, &saved_settings); } int main() { tcgetattr(STDIN_FILENO, &saved_settings); atexit(reset_term_mode); struct termios term_settings; tcgetattr(STDIN_FILENO, &term_settings); term_settings.c_lflag &= ~(ICANON|ECHO); term_settings.c_cc[VMIN] = 1; term_settings.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_settings); char check = 'a'; char int_check = 'a'; int b = 0; printf("want to go in? [y or n]\n"); scanf("%c",&check); if ( check == 'y') { while (1){ printf("Waiting: \n"); scanf("%c", &int_check); if ( int_check == 'q'){ printf("You're out, bye!\n"); break; }; }; } else if ( check == 'n'){ printf("You're not in, see ya!\n"); }else { printf("Please, type 'y' or 'n'\n"); }; return 0; }