[英]C while loop using scanf prints twice when entering more than 1 char of input
I'm trying to read input from stdin in C, where the program performs a few tasks if the entered character is any key but "enter".我正在尝试从 C 中的标准输入读取输入,如果输入的字符是除“输入”之外的任何键,程序将执行一些任务。 I'm using a while loop, and it works fine when user only enters 1 char, but prints a line twice when they enter more than that (entering more than 1 char is fine, the program should generate a new number per each one -- so like if the user enters 'aaa', it generates 3 new numbers.)
我正在使用一个while循环,当用户只输入1个字符时它可以正常工作,但是当他们输入更多时会打印一行两次(输入超过1个字符很好,程序应该为每个生成一个新数字 - - 就像用户输入“aaa”一样,它会生成 3 个新数字。)
So this is the ideal output after entering something like 'eeee'(and it works fine when you enter just one char):所以这是理想的 output 在输入类似 'eeee' 之后(当你只输入一个字符时它工作正常):
CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
but this is what actually happens when you enter 'eeee':但这就是您输入“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):
and this is the part of my code (minimal reproducible version):这是我的代码的一部分(最小的可重现版本):
#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);
}
what is causing this and how can I fix it?是什么原因造成的,我该如何解决?
Try this in your loop:在你的循环中试试这个:
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.