我正在嘗試從 C 中的 stdin 讀取輸入,如果輸入的字符是除“輸入”以外的任何鍵,則程式將執行一些任務。我正在使用一個 while 回圈,當用戶只輸入 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);
}
這是什么原因造成的,我該如何解決?
uj5u.com熱心網友回復:
在你的回圈中試試這個:
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");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368917.html
