我的程序需要获取用户的输入并将其保存到外部文件以供将来参考.这是代码的基本概要.
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)
}
Run Code Online (Sandbox Code Playgroud)
当我运行一个只询问名称并打印该名称的简单测试程序时,一切都很好.它看起来像这样:
int main() {
char name[50];
fprint("What is your name? ");
fgets(name, sizeof(name), stdin);
fputs(name, stdout);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
与工作测试程序不同,我的程序在转移到第二个printf()语句之前不会从用户那里获取任何输入.它确实读取了printf语句中的字符串,但返回值为(null).
至于写入文件,两fprintf行应该这样做,但我无法确认它,因为输入文本没有被正确记录.
这是在我之外声明的函数main().这会影响情况吗?
这是不正确的:
printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n", fputs(name, stdout));
Run Code Online (Sandbox Code Playgroud)
fputs返回一个int,而你printf想要一个字符串%s.
删除fputs,然后传递name给printf:
printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n", name);
Run Code Online (Sandbox Code Playgroud)
使用%s写出来的字符串的文件时:
fprintf(foutfile, "%s", name);
fprintf(foutfile, "%s", description);
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要\n,因为fgets保持\n字符串.
来自评论:我担心的是程序未能[读取输入]的原因
fgets(name, sizeof(name), stdin)
当您从之前的操作中stdin获得额外的\n延迟时,通常会发生这种情况.例如,如果您之前的输入操作已经读取了int使用scanf,您会看到此效果:
scanf("%d", &num);
fgets(name, sizeof(name), stdin);
Run Code Online (Sandbox Code Playgroud)
如果用户按下5 Enter X Enter,程序将设置num为5,但name将设置为单个字符串'\n',而不是'X'.这是因为scanf未能删除'\n'所产生Enter的缓冲,所以scanf发现它,并认为,用户只需输入空字符串.