输入 'Q' 时退出循环

Exit loop when 'Q' is entered

我想用 c 编写一个程序,在循环开始时要求用户输入,如果用户点击 Q 则结束 while 循环。 我正在寻找高效的代码并且没有 fflush() 调用。[我认为用户可以在输入中输入 'a'、'abc'、'ab2c' 等]。 我尝试了以下方式,但如果我按 'a',它还包括 '\0',这会导致额外的循环调用。同样,如果用户输入 'abc' 或 'ab2c' 等,循环将执行多次。

int main (void)
{
    char exit_char = '[=11=]';
    puts ("Entering main()");

    while (1)
    {
        printf ("Please enter your choice: ");

        exit_char = getchar();
        if (exit_char == 'Q')
            break;

        f1();
    }
    return 0;
}

请提出合适的解决方案。

在像你这样的情况下,最好逐行读取输入,然后处理每一行。

#define MAX_LINE_LENGTH 200

char* getInput(char line[], size_t len)
{
   printf ("Please enter your choice: ");
   return fgets(line, len, stdin);
}

int main (void)
{
   char line[MAX_LINE_LENGTH];

   while ( getInput(line, sizeof(line)) )
   {
      if ( toupper(line[0]) == 'Q' )
         break;

      // Process the line

   }    
}

这是你想要的吗?

#include <stdio.h>
#include <ctype.h>

int
main(void)
{
    char buffer[100];

    while (1)
     {
        char *line;

        printf("Please enter your choice: ");
        line = fgets(buffer, sizeof(buffer), stdin);
        if ((line == NULL) || ((toupper(line[0]) == 'Q') && (line[1] == '\n')))
            break;
        printf("Not done yet!\n");
     }
    return 0;
}