当输入超过 1 个字符的输入时,使用 scanf 的 C while 循环打印两次
C while loop using scanf prints twice when entering more than 1 char of input
我正在尝试从 C 中的标准输入读取输入,如果输入的字符是除“enter”之外的任意键,程序会执行一些任务。我正在使用 while 循环,当用户只输入 1 个字符时它工作正常,但当他们输入超过 1 个字符时打印一行两次(输入超过 1 个字符很好,程序应该为每个字符生成一个新数字 - - 就像用户输入 'aaa' 一样,它会生成 3 个新数字。)
所以这是输入类似 'eeee' 的内容后的理想输出(当您只输入一个字符时它工作正常):
CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
但这是当您输入 'eeee':
时实际发生的情况
enter any key for call (q to quit, no enter): CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
这是我的代码的一部分(最小可复制版本):
#include <stdio.h>
#include <stdlib.h>
int main(void){
system("clear");
printf ("CallList: \n");
printf("enter any key for call (q to quit, no enter): ");
char c;
scanf(" %c", &c);
system("clear");
char quit = 'q';
int random;
srand(1063);
while (c != quit){
if (c != '\n') {
random = rand() % 75 + 1;
// does a few functions here, they don't print anything and don't use stdin
}
printf ("CallList: ");
// prints the call list here
printf("\n");
printf("enter any key for call (q to quit, no enter): ");
scanf(" %c", &c);
system("clear");
}
printf("Goodbye! \n");
exit(0);
}
是什么原因造成的,我该如何解决?
在你的循环中试试这个:
while (c != quit){
if (c != '\n') {
random = rand() % 75 + 1;
//here you can add things to your calllist
c = getchar();
}
else {
printf ("CallList: ");
// prints the call list here
printf("\n");
printf("enter any key for call (q to quit, no enter): ");
c = getchar();
system("clear");
}
}
我正在尝试从 C 中的标准输入读取输入,如果输入的字符是除“enter”之外的任意键,程序会执行一些任务。我正在使用 while 循环,当用户只输入 1 个字符时它工作正常,但当他们输入超过 1 个字符时打印一行两次(输入超过 1 个字符很好,程序应该为每个字符生成一个新数字 - - 就像用户输入 'aaa' 一样,它会生成 3 个新数字。)
所以这是输入类似 'eeee' 的内容后的理想输出(当您只输入一个字符时它工作正常):
CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
但这是当您输入 'eeee':
时实际发生的情况enter any key for call (q to quit, no enter): CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
这是我的代码的一部分(最小可复制版本):
#include <stdio.h>
#include <stdlib.h>
int main(void){
system("clear");
printf ("CallList: \n");
printf("enter any key for call (q to quit, no enter): ");
char c;
scanf(" %c", &c);
system("clear");
char quit = 'q';
int random;
srand(1063);
while (c != quit){
if (c != '\n') {
random = rand() % 75 + 1;
// does a few functions here, they don't print anything and don't use stdin
}
printf ("CallList: ");
// prints the call list here
printf("\n");
printf("enter any key for call (q to quit, no enter): ");
scanf(" %c", &c);
system("clear");
}
printf("Goodbye! \n");
exit(0);
}
是什么原因造成的,我该如何解决?
在你的循环中试试这个:
while (c != quit){
if (c != '\n') {
random = rand() % 75 + 1;
//here you can add things to your calllist
c = getchar();
}
else {
printf ("CallList: ");
// prints the call list here
printf("\n");
printf("enter any key for call (q to quit, no enter): ");
c = getchar();
system("clear");
}
}