だから、私はこれまで何度もアップしてきました。しかし、ここのコードは最初の実行時にのみ機能します。つまり、約4つのオプションがあるメニューがあるため、最初に選択されたものだけが機能します。 do whileループが起動してメニューが再び表示されると、選択したメニューに関係なく、メニューが再び表示されます。私はdo whileループを分析しましたが、それに問題はないと確信しています。私は最近、File I/Oについて学び始めたので、忘れたかもしれません。どんな助けでも本当に感謝しています。ありがとう。ここでファイルI/Oコード(C++)
はコードです:
Phonebook.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
};
Phonebook.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;
}
一般に、このような膨大なコードダンプは、スタックオーバーフローの助けを得る方法ではありません。確かに、これを問題を示す最小限の例にすることができます。そして、あなたがそれをやっている間にあなたがそれを解決すれば、あなたのために良い! – dmckee
あなたはループを苦しんでいますか?私はあなたのコードで5を数えました。 – jrok
@Stencil @jrok:彼は文字通り '' 1 - Display phonebook ''を使ってdo whileループを意味します。直接的な原因はストリームが悪い状態になったことですが、すぐには明らかではありませんが、それは悪い状態です。 –