c - 程序不等待文本输入

标签 c

我有这个函数可以从用户那里读取文本并计算每种类型的字母数量。但是,该函数在调用时不会等待用户输入。

我通常会尝试在 %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/

相关文章:

Python正则表达式从C头文件中提取数据

c - 在同一个源上多次运行 C 预处理器是否安全?

c - 将 BST 传递给结构数组

c - 写入 I2C 的缓冲区在读取时不返回

c++ - 使用/dev/input/eventX 和 c/c++ 的设备事件处理

C - 有没有办法处理中间有 NULL 字符的字符串

c - 我是否需要一个单独的线程来为主程序中的 while 循环设置计时器?

c - STM32L1x 停止模式 + RTC 电流过大

c - 频率分析?凯撒密码C

c - C 中的函数指针及其行为