所以我现在已经很久了,也许这就是为什么我无法弄清楚这一点。但是我这里的代码只在第一次执行时起作用,即,因为有一个大约有 4 个选项的菜单,所以它只对第一个被选中的选项起作用。当 do while 循环启动并再次显示菜单时,无论您选择什么,它都会重新显示菜单。我已经分析了 do while 循环,但我很确定这没有任何问题。我最近才开始学习文件 I/O,所以也许我错过了一些东西。任何帮助将非常感激。谢谢。
这是代码:
电话簿.h
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
class Phone
{
public:
void display_phonebook(ifstream& in_stream);// phonebook is the text file
void display_backup(string a[], int size);// backup copy is a string array
void datacopy(ifstream& in_stream, string a[]);// to copy the phonebook to the array
int numberOfLines(ifstream& in_stream);// to check number of lines in the text file
};
电话簿.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include "Phonebook.h"
using namespace std;
void Phone::datacopy(ifstream& in_stream, string a[])
{
int i=0;
while(in_stream.good())
{
string line;
getline(in_stream, line);
a[i]=line;
i++;
}
int s=i;
for(int x=0;x<s;x++)
{
cout<<a[x]<<endl;
}
}
int Phone::numberOfLines(ifstream& in_stream)
{
int count=0;
while(!in_stream.eof())
{
string line;
getline(in_stream, line);
count++;
}
return count;
}
void Phone::display_phonebook(ifstream& in_stream)
{
while(!in_stream.eof())
{
string line;
getline(in_stream, line);
cout<<line<<endl;
}
}
void Phone::display_backup(string a[], int size)
{
for(int i=0;i<size;i++)
{
cout<<a[i]<<endl;
}
cout<<endl;
}
主文件
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include "Phonebook.h"
using namespace std;
int main()
{
Phone p;
int size=0;
ifstream fin;
ofstream fout;
char file[50], ch;
string backup[50];
int flag=0;
do
{
cout<<"Enter the name of the file: "<<endl;
cin>>file;
fin.open(file);
cout<<endl;
if(fin.fail())
{
cout<<"File not found!"<<endl<<endl;
cout<<"Try Again? (Y/N)"<<endl;
cin>>ch;
if(ch=='N' || ch=='n')
{
cout<<"Terminating..."<<endl;
system("PAUSE");
exit(1);
}
}
else
{
flag=1;
}
}
while((ch=='Y' || ch=='y') && flag==0);
cout<<"Success! File Opened"<<endl<<endl;
int choice;
do
{
cout<<"1 - Display phonebook"<<endl;
cout<<"2 - Display backup copy"<<endl;
cout<<"3 - Update backup copy"<<endl;
cout<<"4 - Exit"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
if(choice==1)
{
p.display_phonebook(fin);
}
else if(choice==2)
{
size=p.numberOfLines(fin);
p.display_backup(backup, size);
}
else if(choice==3)
{
p.datacopy(fin, backup);
}
}
while(choice!=4);
fin.close();
fout.close();
system("PAUSE");
return 0;
}