Create a C++ program which shows the given menu items:
1. Create (The create option will create a text file named "mytext.txt").
* This option should save accept basic personal information of the user such as name, course, email and contact number.
2. Read (The read option will read the contents of the file.)
3. Append (The append option will add text contents in mytext.txt)
* This option should add a string inputted by the user
4. Exit (The exit option will terminate the program which means the program is in loop while running)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void append(const char* filename, string str);
int main() {
int status = 0;
string line, str;
const char* filename = "mytxt.txt";
ifstream file;
cout << "Select option:" << endl;
cout << "1 - Create" << endl;
cout << "2 - Read" << endl;
cout << "3 - Append" << endl;
cout << "4 - Exit" << endl;
while (status == 0) {
cin >> status;
switch (status) {
case 1:
if (file.is_open()) {
file.close();
}
file.open(filename, fstream::trunc | fstream::in | fstream::out);
status = 0;
break;;
case 2:
if (!file.is_open()) {
file.open(filename, fstream::in);
}
file.seekg(0, std::ios::beg);
while (!file.eof()) {
getline(file, line);
str += line;
}
cout << str << endl;
str = "";
status = 0;
break;
case 3:
cout << "Enter text:" << endl;
cin >> str;
append(filename, str);
str = "";
status = 0;
break;
case 4:
break;
default:
status = 0;
break;
}
}
return 0;
}
void append(const char* filename, string str) {
ofstream file(filename, fstream::out | fstream::app);
file << str;
}
Comments
Leave a comment