【问题标题】:user input(string) writing to a file until the user gives an empty line用户输入(字符串)写入文件,直到用户给出一个空行
【发布时间】:2018-06-12 07:50:47
【问题描述】:

我正在将用户输入(字符串)写入文件。但是我想在用户按下回车键而不输入任何字符串时结束程序。 例如 输入:

你好怎么样 你是!

结束程序。

我试图以这种方式做到这一点。但是当用户不输入任何内容时它不会停止。

这是我的代码:

#include <stdio.h>
#include <stdlib.h> 


int main(void)
{

    char buffer[1000];

    char sent[1000];
    FILE* ifp = fopen("text.txt", "w");


        while (sscanf(buffer,"%s",sent) == 1) {

        fprintf(ifp,"%s",buffer);

       }
    fclose(ifp);


    return 0;
}

【问题讨论】:

  • 欢迎来到本站。您的示例中是否缺少一些代码?这个例子实际上并没有要求用户输入任何内容。此外,您应该真正检查来自 fopen() 的返回值 - 就像在 if (!ifp) { perror("fopen"); exit(1); } 中一样。
  • 无论如何...如果您尝试读取字符串(字符数组),最好使用fgets() 而不是sscanf()。请记住,您必须去掉换行符。

标签: c


【解决方案1】:

在你正在做的代码中:

while (sscanf(buffer,"%s",sent) == 1) {

但没有在buffer中填写任何内容。
正如大卫柯林斯所建议的,它对用户 fgets() 而不是 sscanf() 更好。你可以这样做:

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

int main() {
    char input[LINE_MAX];
    FILE *ifp = fopen("text.txt", "w");

    if (ifp == NULL) {
        perror("fopen"); 
        exit(EXIT_FAILURE);
    }

    while (fgets(input, LINE_MAX, stdin) != NULL) {
        if (input[0] == '\n')
            break;

        fprintf (ifp, "%s", input);
    }

    fclose (ifp);
    return 0;
}

【讨论】:

    【解决方案2】:

    尝试将您的代码替换为:

    char *buffer;
    
    if ((buffer = malloc(sizeof(char) * 1000)) == NULL)
        exit(EXIT_FAILURE);
    memset(buffer, 0, 1000);
    
    while (read(0, buffer, 1000) != 0) {
        if (strcmp(buffer, "\n") == 0)
           break;
        fprintf(ifp,"%s",buffer);
        memset(buffer, 0, 1000);
     }
    

    并提醒用户他不能写超过 1000 个字符的消息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2018-07-07
      • 2021-08-13
      相关资源
      最近更新 更多