将文本文件的每一行转换为数组 c
Turn each line of a text file into an array c
我正在尝试从文本文件中获取输入,然后反转每一行,然后输出回不同的文本文件。由于某种原因,该程序只对第一行执行此操作,而不会移动到第二行。我不明白这一点,因为它应该一直持续到达到 EOF。
如果文件没有以换行符结尾,您永远不会打印最后一行,因为您只在读取换行符时调用 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;
}
我正在尝试从文本文件中获取输入,然后反转每一行,然后输出回不同的文本文件。由于某种原因,该程序只对第一行执行此操作,而不会移动到第二行。我不明白这一点,因为它应该一直持续到达到 EOF。
如果文件没有以换行符结尾,您永远不会打印最后一行,因为您只在读取换行符时调用 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;
}