我需要检查用户输入是否包含点以及是否按下了回车键。 (文本文本文本.[Enter]
)
如果是,则不要将该行写入文件并退出,否则继续输入并将行写入文件。
这是我到目前为止所拥有的代码:
FILE *File;
char *fileName = argv[1];
char *ptr;
char name[20];
File = fopen(fileName, "r");
scanf("%s", name);
fprintf(File, "%s\n", name);
for (ptr = name; *ptr!= '\0'; ptr++)
{
if (*ptr == '.')
{
printf("Exit");
fclose(File);
exit(0);
}
else
{
// How to make user continue to input and write to file?
}
}
最佳答案
不要关闭您没有打开的文件。在验证名称不包含点的循环之后使用文件(打开它,写入其中,然后关闭它),如下所示:
char *ptr;
char name[20];
FILE *f;
scanf("%s", name);
printf("%s\n", name);
for (ptr = name; *ptr!= '\0'; ptr++) {
if (*ptr == '.') {
printf("Exit");
exit(0);
}
}
f = fopen(name,"w"); // open for writing
if (f==NULL) { fprintf(stderr,"Can't open the file\n"); exit(1); }
fprintf(f,"Hello"); // write something
fclose(f); // close after using the file
关于c - 如何以编程方式检查输入是否包含点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34187280/