gpt4 book ai didi

c++ - C++ 中的文件 I/O 代码

转载 作者:行者123 更新时间:2023-11-30 00:56:19 26 4
gpt4 key购买 nike

<分区>

所以我已经起床很长时间了,也许这就是我无法弄清楚的原因。但是我这里的代码将只在第一次执行时起作用,即,因为有一个包含大约 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;
}

main.cpp

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com