我正在尝试编写一个带有菜单的程序,该菜单以几种不同的方式从文本文件中读取。我仍在处理菜单选项#2(从文件末尾向后读取),但我无法理解我做错了什么。我已经在这里待了几天了,只是找不到任何好的资源来帮助解决这个问题。任何帮助,将不胜感激。
#include <iostream>
#include <string>
#include <iomanip>
#include <istream>
#include <math.h>
#include <fstream>
using namespace std;
const int SIZE = 20;
typedef char String[SIZE];
//prototypes
void Menu(int &);
void ReadFile(ifstream &);
void BackwardFile(ifstream &,long &);
long CountFile(ifstream &,long &);
int main()
{
char filename[]= "grades.txt";
int choice;
long numBytes;
ifstream InList;
InList.open(filename);
if(InList.good())
{
do
{
Menu(choice);
switch(choice)
{
case 1:
ReadFile(InList);
break;
case 2:
CountFile(InList,numBytes);
BackwardFile(InList,numBytes);
break;
case 3:
cout << "Pick a start position between 0 - " << numBytes << endl;
break;
/*case 4:*/
case 5:
cout << "\n GOOD BYE." << endl << endl;
break;
}
}while (choice != 5);
}
else
cout << "File did not open successfully." << endl << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void Menu(int &choice)
{
cout << "\n Choose an option:";
cout << "\n...................................";
cout << "\n 1- Display All Contents of the File";
cout << "\n 2- Display Content in Reverse Order";
cout << "\n 3- Display from Point A to Point B";
cout << "\n 4- Display from Point B to Point A";
cout << "\n 5- Exit";
cout << "\n\n Enter your choice: ";
cin >> choice;
}
void ReadFile(ifstream& inFile)
{
char byte;
inFile.clear();
cout<< "\nReading contents from the file:" <<endl;
if(inFile)
{
inFile.get(byte);
while(inFile.good())
{
cout << byte;
inFile.get(byte);
}
}
inFile.close();
}
void BackwardFile(ifstream& inFile, long& numBytes)
{
char byte;
inFile.clear();
cout<< "\nReading contents backwards from the file:" <<endl;
inFile.seekg(numBytes, ios::end);
while(inFile)
{
inFile.get(byte);
cout << byte;
numBytes--;
inFile.seekg(numBytes);
}
inFile.close();
}
long CountFile(ifstream& inFile, long& numBytes)
{
inFile.seekg(0L, ios::end);
numBytes = inFile.tellg();
return numBytes;
}