c - 如何以编程方式检查输入是否包含点?

标签 c for-loop input printf

我需要检查用户输入是否包含点以及是否按下了回车键。 (文本文本文本.[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/

相关文章:

c - 与 SSE 的并行前缀(累积)总和

javascript - Nunjucks:在 for 循环中从数组中选择特定项目

c++ - 动态设置 for 循环的初始化、条件和 in/decrementation

c# - 从用户处获取输入以填充 C# 中的列表

python - 如何使用Python从同一文本文件中分离不同的输入格式

HTML5 输入日期时间本地

C 程序在 EOF 检查时挂起

c++ - 使用 C++ API 开发 Google Pepper 可信插件时如何设置链接器标志

循环浏览一些数字

java - 创建一个循环,在遇到冒号字符之前返回字符