【问题标题】:Why does this code write input on second line?为什么这段代码在第二行写输入?
【发布时间】:2020-09-08 07:48:18
【问题描述】:
#include <stdio.h>
#include <string.h>


void main() {

    FILE* fp;
    char line[1024];
    char filename[1024];
    int length;
    int counter=0;

    while (1) {
       // fopen(filename, "w");
        int op = 0;
        printf("1. new file");
        scanf("%d", &op);

        switch (op) {

        case -1: break;
        case 1:

            printf("filename>>");
            scanf("%s", filename);
            length = strlen(filename);
            printf("length = %ld \n", strlen(filename));
            filename[length] = '.';
            filename[length + 1] = 't';
            filename[length + 2] = 'x';
            filename[length + 3] = 't';
            filename[length + 4] = '\0';

            fp=fopen(filename, "w");

            while (fgets(line, sizeof line, stdin) != NULL)
            { 
                if (line[0] == 'q' || line[0] == 'Q')
                {
                    printf("end of line \n");
                    fclose(fp);
                    break;
                }
                else
                    fputs(line, fp);
            }
        }
    }
}

我制作了这段代码来制作我想要的文本文件。 但问题是, 当我运行这个程序时,它从第二行写入输入,而不是第一行。

为什么会这样? 我想从第一行写输入。 如何更改此代码以在第一行编写?

【问题讨论】:

  • 我读过,但我不能完全理解。

标签: c io write


【解决方案1】:

可能的原因是您在标准输入上的 scanf 之后使用 fgets。

Using scanf and fgets in the same program?

【讨论】:

    【解决方案2】:
    scanf("%s", filename);
    

    当您从键盘输入文件名时,您输入文件名,然后按 ENTER。 scanf 函数读取 filename 但不使用 ENTER 字符。然后当你使用fgets 时,它会读取这个 ENTER 字符,然后在你的文件中写入一个空行。

    为了解决这个问题,你可以在scanf("%s", filename);之后使用getchar()来消耗回车符。您应该在scanf 函数中的%s 之前添加1023Disadvantages of scanf

    scanf("%1023s", filename);
    getchar();
    

    或者您可以使用fgets 代替:

    fgets(filename, sizeof(filename), stdin);
    

    还有一点,switch 语句中的break 并不能帮助您退出第一个while 循环(while (1) {...})。您应该使用一个条件来退出此循环,例如:

    char ch = 'a';
    while (ch != 'q') {
    
      ...
      switch (op) {
          case -1: ch = 'q'; break; // type -1 will exit the first while loop.
    

    switch 应该有 default 例外情况。

     switch (op) {
        ...
        default:
           // handle the exception here.
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多