I want to make a simple file input output program with an external class "File_Opening_and_Closing.cpp” when I use ”getline ()” function without any loop it works fine but when I use ”getline ()” function with do while loop in “main.cpp” it crushes.
Please tell me where the problem is and how I solve it?
main.cpp
#include<iostream>
#include<fstream>
#include "File_Opening_and_Closing.h" using namespace std;
int main() {
int i=1;
char file_make='y';
char file_insert='y';
do
{
File_Opening_and_Closing file[i];
do
{
file[i].put_data();
file[i].show_data();
cout<<"Do you want to insert text again ? 'y' OR 'n'"<<endl;
cin>>file_insert;
}while(file_make=='y');
i++;
cout<<"Do you want to Make another file ? 'y' OR 'n'"<<endl;
cin>>file_make;
}while(file_insert=='y');
return 0;}
with out loop working fine >>
int main() {
File_Opening_and_Closing file;
file.put_data();
file.show_data();
return 0;}
File_Opening_and_Closing.cpp
#include "File_Opening_and_Closing.h"
File_Opening_and_Closing::File_Opening_and_Closing()
{
cout<<"Enter the file name and type => ";
cin>>file_name;
}
void File_Opening_and_Closing::put_data(){
ofstream file_out;
file_out.open(file_name);
cin.ignore();
cout<<"Enter the string => ";
cin.ignore();
// getline is not working here!
getline(cin,data);
data = "Hello World!";
file_out<<data;
file_out.close();
}
void File_Opening_and_Closing::show_data(){
ifstream file_in;
file_in.open(file_name);
getline(file_in,data);
cout<<data;
file_in.close();
}
File_Opening_and_Closing.h
#ifndef FILE_OPENING_AND_CLOSING_H
#define FILE_OPENING_AND_CLOSING_H
#include<iostream>
#include<fstream>
using namespace std;
class File_Opening_and_Closing
{
private:
string file_name;
string data;
public:
File_Opening_and_Closing();
void put_data();
void show_data();
protected:
};
#endif // FILE_OPENING_AND_CLOSING_H