简体   繁体   English

将文本文件的每一行转换为数组c

[英]Turn each line of a text file into an array c

I'm trying to take input from a text file, and then reverse each line, and output back into a different text file. 我正在尝试从文本文件中获取输入,然后反转每一行,然后输出回到另一个文本文件中。 For some reason, the program only dos this for the first line, and does not move onto the second line. 由于某种原因,该程序仅在第一行执行此操作,而不会移至第二行。 I don't get this because it should keep going until it hits EOF. 我不明白这一点,因为它应该一直持续到达到EOF为止。

If the file doesn't end with a newline, you'll never print the last line, because you only call reverse(array) when you read the newline character. 如果文件不以换行符结尾,则将永远不会打印最后一行,因为在读取换行符时,您仅调用reverse(array)

You can solve this by calling it again after the while loop is done. 您可以通过在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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM