将用户输入字符串写入文件C
我的程序需要接受用户输入并将其保存到外部文件以供将来参考。这是代码的基本概述。将用户输入字符串写入文件C
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
。
从评论:我关心的是,为什么项目未能[阅读输入对于
fgets(name, sizeof(name), stdin)
当您的stdin
有一个额外的\n
从以前的操作挥之不去经常会发生冲突。例如,如果你以前的输入操作已经阅读使用scanf
的int
,你会看到这样的效果:
scanf("%d", &num);
fgets(name, sizeof(name), stdin);
如果用户按下 输入X输入,该计划将将num
设置为5
,但name
将设置为单个'\n'
的字符串,而不是'X'
。这是因为scanf
未能删除'\n'
生成的从缓冲区输入,所以scanf
发现它,并认为用户刚刚输入了一个空字符串。
虽然这是有用的信息,但它没有解决主要问题:程序不会接受用户的任何输入。 – Naltroc
@Naltroc为什么,它应该!需要检查的一点是,在调用'newActivity'之前,输入缓冲区中没有'\ n'。如果您使用'%d','%f'或其他数字格式说明符调用'scanf',可能会发生这种情况。 – dasblinkenlight
,它确实解决了返回正确字符串的问题。谢谢你。 我仍然对第一块代码第7行感到困惑!它不需要我的意见。相反,它会打印9,运行第10行并接受更长的字符串,然后将该字符串作为“%s”描述返回,就像它应该那样。 我的问题是为什么程序没有为'fgets(name,sizeof(name),stdin)'做这个。 – Naltroc
此外,为什么函数有无用的输入参数'finput'? –
你是用'%d'ecimal格式说明符'printf'字符串'name'和'description'。这会让你的程序调用未定义的行为。有可能与'name'和'description'有关的任何事情都被优化掉了,否则就会被抛弃。你有没有尝试过使用调试器?编辑:正如dasblinkenlight指出的那样,这不是你唯一的问题。请考虑你在写什么。 –
什么是'fprint(“你叫什么名字?”)''main()'的第3行? 'newActivity()'在哪里被调用? – user3078414