gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:22:37 25 4
gpt4 key购买 nike

我认为我的代码问题出在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com