c - 第二次调用时会跳过的 fgets

标签 c fgets

我认为我的代码问题出在我的 fgets 上,但我不知道如何修复它。因此,当我第一次调用该函数时,一切正常,但如果第二次调用该函数,该函数会跳过 printf 之后的所有内容。

所以输出将是:

Output:
Please enter x and y coordinates separated by a comma for the piece you wish to enter: 3,4
x: 3, y:4
Please enter x and y coordinates separated by a comma for the piece you wish to enter: x:
, y:

这是代码:

void functioncall()
{
    char coord[4];
    printf("Please enter x and y coordinates separated by a comma for the piece you wish to place: ");
    fgets(coord, 4, stdin);

    char *xcoord = strtok(coord, ",");
    char *ycoord = strtok(NULL, " ");
    if (!ycoord)
    {
        ycoord = "";
    }

    printf("x: %s, y: %s\n", xcoord, ycoord);
}

第二次调用时无法输入。

最佳答案

您看到的行为的原因是 coord 数组的大小。当您将大小指定为 4 时,这意味着您可以存储 1 位数字、1 个逗号、1 位数字和 1 个空字节 - 这不会为换行符留下空间,因此第二次调用该函数(仅)读取换行符,这不能很好地解析。

您应该留出更多空间 - 用户在输入内容时具有无穷无尽的创造力(前导空格、尾随空格、中间空格、符号、前导零等)。我倾向于使用 4096 来表示单行输入 — 部分是为了震撼值,也是因为如果有人愿意在一行上写一篇 4 页的文章,他们应得的。

这段代码对我有用:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void functioncall(void)
{
    char coord[4096];
    printf("Please enter x and y coordinates separated by a comma for the piece you wish to place: ");
    if (fgets(coord, sizeof(coord), stdin) == 0)
    {
        fprintf(stderr, "Got EOF in %s\n", __func__);
        exit(EXIT_FAILURE);
    }
    const char delims[] = ", \n\t";

    char *xcoord = strtok(coord, delims);
    char *ycoord = strtok(NULL, delims);
    if (!ycoord)
    {
        ycoord = "";
    }

    printf("x: [%s] y: [%s]\n", xcoord, ycoord);
}

int main(void)
{
    functioncall();
    functioncall();
    return 0;
}

运行示例(程序名cd19,源文件cd19.c):

$ ./cd19
Please enter x and y coordinates separated by a comma for the piece you wish to place: 234 , 495
x: [234] y: [495]
Please enter x and y coordinates separated by a comma for the piece you wish to place: 1,2
x: [1] y: [2]
$

分隔符的选择可确保 234 , 495 示例正常工作(制表符是可选的,但不一定是坏主意)。但是,这确实意味着用户没有义务输入逗号。

关于c - 第二次调用时会跳过的 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39178296/

相关文章:

c中的循环移位

c - 从文本文件中读取未知长度的字符串并打印它们

c - STDIN 重定向 : how to make program end once fgets() reads an expected ending line

c - C语言逐行查找文件中的单词

C——scanf 或 fgets 似乎都没有执行

c - Atmega328 上的韦根协议(protocol)实现

c - 递增字符数组指针

c++ - 使用 clang 捕获设置但未使用的参数

c - 通用指针和void指针有什么区别?

C: 如何在不记录 ENTER (\n) 的情况下获取用户输入?