我有这个函数可以从用户那里读取文本并计算每种类型的字母数量。但是,该函数在调用时不会等待用户输入。
我通常会尝试在 %c 之前放置一个空格,但是添加这个空格会使程序在您按回车键后不会继续。
void ReadText(int histo[], int *max) {
int i;
char userInput;
printf("ENTER A LINE OF TEXT:\n");
do{
if (scanf("%c", &userInput) != 1)
break;
if(userInput >= 97 && userInput <= 122)
histo[userInput-97] = histo[userInput-97] + 1;
else if(userInput >= 65 && userInput <= 90)
histo[userInput-65] = histo[userInput-65] + 1;
}while(userInput != '\n');
for(i = 0; i < 26; i++)
printf("%d ", histo[i]);
*max = histo[0];
for(i = 0; i < 25; i++)
if(histo[i] > *max)
*max = histo[i];
}
int main() {
char command;
int i, max;
int histo[26] = {0};
//User Input Validation
do{
printf("Enter command (C, R, P, or Q): ");
scanf(" %c", &command);
switch(command) {
case 'C': case 'c':
for(i = 0; i < 25; i++)
histo[i] = 0;
break;
case 'R': case 'r':
ReadText(histo, &max);
break;
case 'P': case 'p':
DrawHist(histo, max);
break;
case 'Q': case 'q':
return 0;
default:
printf("Invalid Command %c", command);
printf("\n");
}
}while(1);
return 0;
}
最佳答案
问题出在您的主函数中——您调用 scanf("%c"
来读取命令,这会在输入缓冲区中留下换行符。因此,当您调用 ReadText 时,它首先读取换行符,然后立即返回。
在调用 ReadText 之前,您需要添加一些代码来读取(并丢弃)当前输入行的其余部分。
关于c - 程序不等待文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55701242/