gpt4 book ai didi

c - 将用户输入的字符串写入 C 文件

转载 作者:太空狗 更新时间:2023-10-29 16:01:02 25 4
gpt4 key购买 nike

我的程序需要接受用户的输入并将其保存到外部文件以供将来引用。这是代码的基本轮廓。

void newActivity(FILE *foutput) {
char name[31];
char description[141];
finput = fopen("activities.txt", "a");

printf("\n What is the name of your activity (up to 30 characters):\n");
fgets(name, sizeof(name), stdin);

printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n",
fputs(name, stdout));
fgets(description, sizeof(description), stdin);

if (finput == NULL) {
printf("\nCould not open file.");
exit(1);
}

fprintf(foutfile, "%s\n", name);
fprintf(foutfile, "%s\n", description);

fclose(foutfile)
}

当我运行一个简单的测试程序时,它只要求输入一个名称并打印该名称,一切正常。它看起来像这样:

int main() {
char name[50];
fprint("What is your name? ");
fgets(name, sizeof(name), stdin);
fputs(name, stdout);
return 0;
}

与工作测试程序不同,我的程序在移动到第二个 printf() 语句之前不接受用户的任何输入。它确实读取 printf 语句中的字符串,但返回值 (null)

至于写入文件,两行 fprintf 应该可以,但我无法确认,因为输入的文本没有被正确记录。

这是在我的 main() 之外声明的函数。这对情况有影响吗?

最佳答案

这是不正确的:

printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n", fputs(name, stdout));

fputs 返回一个 int,而您的 printf 需要一个字符串 %s

删除fputs,并将name传递给printf:

printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n", name);

将字符串写入文件时使用%s:

fprintf(foutfile, "%s", name);
fprintf(foutfile, "%s", description);

请注意,您不需要 \n,因为 fgets\n 保留为字符串。

From the comments: My concern is why the program is failing to [read input] for fgets(name, sizeof(name), stdin)

当您的 stdin 有一个额外的 \n 从之前的操作中挥之不去时,通常会发生这种情况。例如,如果您之前的输入操作是使用 scanf 读取 int,您将看到以下效果:

scanf("%d", &num);
fgets(name, sizeof(name), stdin);

如果用户按下5 Enter X Enter,程序将设置num5,但 name 将设置为带有单个 '\n' 的字符串,而不是 'X' 。这是因为 scanf 未能从缓冲区中删除由 Enter 产生的 '\n',所以 scanf 找到了它,并认为用户刚刚输入了一个空字符串。

关于c - 将用户输入的字符串写入 C 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38685081/

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