【问题标题】:Turn each line of a text file into an array c将文本文件的每一行转换为数组 c
【发布时间】:2015-10-07 20:52:44
【问题描述】:

我正在尝试从文本文件中获取输入,然后反转每一行,然后输出回不同的文本文件。出于某种原因,程序只对第一行执行此操作,而不会移动到第二行。我不明白这一点,因为它应该一直持续到它到达 EOF。

【问题讨论】:

  • while ( (temp=getchar()) != EOF ) 允许您删除temp=getchar(); 的三个副本。您可能还想在reverse 函数的返回之前添加一个putchar('\n');
  • 此外,您发布的代码将从stdin 读取并写入stdout。这是你真正的程序吗?
  • @iharob 他正在使用 I/O 重定向来读写文件
  • 您确定输入文件的第二行以换行符结尾吗?当您读取换行符时,您只会打印出反转的行,因此如果没有,您将不会打印最后一行。
  • 你使用的函数定义为int getchar();,所以你需要使用int temp而不是char temp。否则你无法区分字节值0xFF 和标志EOF

标签: c arrays file text line


【解决方案1】:

如果文件不以换行符结尾,您将永远不会打印最后一行,因为您只会在读取换行符时调用reverse(array)

您可以在while 循环完成后再次调用它来解决此问题。

int  main() {
    char temp;
    char  array[80] = "";
    int count = 0;
    temp = getchar();  //Start on first Character
    while (temp != EOF) {   //loop through the entire file
        if (temp == '\n') {  //If it is the end of a line
            reverse(array);   //Print out the reversed line
            memset(array,0,80);  //clear the array
            count = 0;  //reset count
            temp = getchar(); //Advance getchar
        }
        else {  //If it is not the end of the line
            array[count] = temp;  //Store the char in the array
            count++;   //advance count
            temp = getchar();   //advance getchar
        }
    }
    if (count > 0) {
        reverse(array);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多