I am trying to print a file in reverse order. I am using arrays to save each lines data. So far I was able to print every line in a normal order.
index is the number of lines I am referring to and FuncIndex the same thing but has been declared again in the function.
file = fopen("../quotes.data","r");
while (NumOfField == 8) {
NumOfField = fscanf(file,"%d,%c,%d,%d,%c,%c,%lf,%lf", "e[index], &roomletter[index], &length[index], &width[index], &paint[index], &ceiling[index], &cost[index], &setup_cost[index]);
index++;
}
index--;
fclose(file);
In Function:
int FuncIndex;
for (FuncIndex = 0; FuncIndex <= index; FuncIndex++) {
printf("\n%5d %1c %3d %3d %1c %1c %8.2lf %6.2lf", quote[FuncIndex], roomletter[FuncIndex], length[FuncIndex], width[FuncIndex], paint[FuncIndex], ceiling[FuncIndex], cost[FuncIndex], setup_cost[FuncIndex]);
}
Now I tried changing the for loop to:
for (FuncIndex = index; FuncIndex >= 0; FuncIndex--) >
But the output prints empty. Although when I change the 0 to any number, that corresponding line gets printed.
The output That prints is:
Quote Room Length Width Paint Ceiling Cost Setup
===== ==== ====== ===== ===== ======= ======= =====
531 A 10 10 b n 96.00 100.00
531 B 15 15 b n 144.00 0.00
531 C 20 20 b n 192.00 0.00
I am looking to get this output reversed like:
Quote Room Length Width Paint Ceiling Cost Setup
===== ==== ====== ===== ===== ======= ======= =====
531 C 20 20 b n 192.00 0.00
531 B 15 15 b n 144.00 0.00
531 A 10 10 b n 96.00 100.00
Please excuse me if I putted the output in the code section because then the formatting would change
Thank you.
Maybe you should post all your code (however, try to reduce it to minimum). This works for me:
File input.txt
530 A 531 B 532 C
#include <stdio.h>
#include <conio.h>
#define MAX_LINES 50
int main()
{
FILE* file;
int NumOfField = 2;
int index = 0;
char roomLetter[ MAX_LINES ];
int quote [ MAX_LINES ];
file = fopen("input.txt","r");
while ( NumOfField == 2 ) {
NumOfField = fscanf(file,"%d %c\n", "e[index], &roomLetter[index]);
index++;
}
fclose(file);
index--;
for(; index >=0; index-- )
printf( "%d %c\n", quote[index], roomLetter[index] );
getch();
return 0;
}
Ok here is the answer to my question:
the EOF was the trick
for (FuncIndex = index; FuncIndex != EOF; FuncIndex--)
Basically, in here you are saying that whatever the number of index is (Number of Lines) put it in the FuncIndex and then one by one (from the highest number) check each line until its not the end of line anymore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.