-2

I'm trying to write a program to read from a file and display the text backwards. - My loop backward loop is not working. Any suggestions? - Also if I'm reading a file that only contain floats integers or floats, how would I display them all as float?

Thanks,

#include <iostream>
#include <fstream>
using namespace std;

void seeReverseText(char fileName[])
{
   ifstream fin(fileName);
   if (fin.fail())
   {
      cout << "Error opening file " << fileName << endl;
      return;
   }

   cout.setf(ios::showpoint);
   cout.precision(2);
   cout.setf(ios::fixed);

   int i = 0;
   cout << "New order:\n";
   while (!fin.eof())
   { 
     // this is what I was trying to do
     //  i++;
     // for (i--; i >= 0; i--)
     //   fin >> fileName[i];
     //  cout << "' " << fileName[i] << "'";
      fin >> fileName;
      cout << fileName  << endl;
   }
   fin.close();
}


int main()
{

   char fileName[256];
   cout << "Enter the filename: ";
   cin  >> fileName;


   seeReverseText(fileName);

   return 0;
}

1 Answers1

0

Try something more like this instead:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

void seeReverseText(const std::string &fileName)
{
   std::ifstream fin(fileName);
   if (!fin)
   {
      std::cout << "Error opening file " << fileName << std::endl;
      return;
   }

   std::cout.setf(std::ios::showpoint);
   std::cout.precision(2);
   std::cout.setf(std::ios::fixed);

   std::cout << "New order:\n";

   std::string line;
   while (std::getline(fin, line))
   { 
      std::reverse(line.begin(), line.end());
      std::cout << line << std::endl;
   }
}

int main()
{
   std::string fileName;

   std::cout << "Enter the filename: ";
   if (std::cin >> fileName)
      seeReverseText(fileName);

   return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770