Answer to Question #322260 in C++ for sander

Question #322260

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)


1
Expert's answer
2022-06-27T17:01:02-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog