c - fgets 不会停止读取用户输入

标签 c fgets

我在 reddit 上发现了一些关于制作一个程序来总结所有 DnD 骰子的挑战。抛出次数是无限的,因此我创建了这个 while 循环。

我使用 fgets 输入字符串,(我不能只输入整数,因为输入例如是 1d3,其中 1 是掷出的骰子数,3 是掷出的骰子面数。)

当提示用户输入骰子时,fgets 永远不会停止读取用户输入。

例如:

To end inputting dice type 0
1d3 
1d4
1d5
0
0
^C

主要功能:

int main(void)
{
    char input[MAXSIZE];
    int sum = 0;
    printf("To end inputting dice type 0\n");
    while(*(input) != 0);
    {
        fgets(input, sizeof(input), stdin);
        printf("Debug: input = ");
        puts(input);
        printf("\n");
        sum += dice(input);
        printf("Debug: sum = %d\n", sum);
    }
    printf("Sum of dice rolls is %d.", sum);
    return 0;
}

最佳答案

首先,字符输入0的字面值不是0。在 ASCII ,它是 48(十进制)。

尝试

 while(*(input) != '0')  // (1) - use the character literal form
                         // (2) remove the ;

也就是说,standard output is usually line buffered .如果要在终端中查看输出,则需要强制刷新。您可以通过以下任一方式做到这一点

  • 添加换行符

     printf("Debug: input = \n");
    
  • 使用fflush(stdout)

关于c - fgets 不会停止读取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361729/

相关文章:

c - 如何在 C 中仅接受用户输入的特定字符

c - 指针类型不兼容的警告

c - 结构的扫描使程序崩溃

c - 从 fgets() 输入中删除尾随换行符

c - 如何将文件引用为 fgets() 的流?

c - scanf 和 fgets 在同一个程序中

c - 使用 fgets 只读取文件的一部分

c - float 一个( float );意义?

c - 指针数组初始化

c - fscanf 问题 - 无法从文件中提取字符串