从文件中读取并向后显示

时间:2016-03-11 01:42:34

标签: c++

我试图编写一个程序来读取文件并向后显示文本。 - 我的循环后向循环不起作用。有什么建议? - 此外,如果我正在读取一个只包含浮点整数或浮点数的文件,我将如何将它们全部显示为浮点数?

谢谢,

#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 个答案:

答案 0 :(得分:0)

尝试更像这样的东西:

#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;
}