I coded a program to open a file show content modify, clear or append some text to it.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char name[100];
char content[100];
char write[200];
int sel;
cout<< "Enter the name of the file to open: ";
cin>> name;
cin.ignore();
ifstream a_file ( name );
a_file.getline ( content, 100);
cout<< "Contents of the file: "<< content;
a_file.close();
cout<< "\nSelect an action from below.\n1.)Modify 2.)Clear 3.)Add some more text: ";
cin>> sel;
if (sel == 1)
{
ofstream b_file ( name );
cout<< "Enter something to write to the file: ";
cin.getline (write, 200);
b_file<< write;
b_file.close();
cin.ignore();
cout<< "File modified successfully.";
} else if (sel == 2)
{
ofstream b_file (name, ios::trunc);
cout<<"File cleared Successfully.";
b_file.close();
} else if ( sel == 3 )
{
ofstream b_file (name, ios::app);
cout<< "Enter something to add to the file: ";
cin.getline ( write, 200 );
b_file<< write;
cin.ignore();
cout<< "Text added to the file seccessfully.";
b_file.close();
}else {
cout<< "Bad selection press 'Enter' to close";
}
cin.get();
}
I'm stuck in if codes
Code:
else if (sel == 2)
{
ofstream b_file (name, ios::trunc);
cout<<"File cleared Successfully.";
b_file.close();
}
works fine but the other twos only open and clear file but don't write to file while they have to do so any help will be welcomed.