I\'m trying to read read from a file a display it in the reverse order. Example,
ID: 3676658 • Letter: I
Question
I'm trying to read read from a file a display it in the reverse order.
Example, if the file reads 1 2 3, I would like to read from it and display 3 2 1.
From what it is right now, it reads the file okay, but it does not display in the reverse order.
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream> #include <fstream> using namespace std; void seeReverseText(char fileName[]) { ifstream fin(fileName); if (fin.fail()) { cout << "error "; return; } int i = 0; while (!fin.eof()) { // (how I think I should go about) // i++; // for (i--; i >= 0; i--) // fin >> fileName[i]; // cout << fileName[i] << endl; // how to display in the correct order fin >> fileName; cout << fileName << endl; } fin.close(); } int main() { char fileName[256]; cout << "Filename: "; cin >> fileName; cout << "New order: "; seeReverseText(fileName); return 0; }
Explanation / Answer
Please find an alternate way here :
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
char str[line.size()+1];
strcpy(str, line.c_str());
int l; //Hold length of string
for(l = 0; str[l] != ''; l++); //finding length of string
int temp;
for(int i = 0, j = l - 1; i < l/2; i++, j--)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
cout << str << ' ';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}