Answer to Question #180102 in C++ for saif islam

Question #180102

There are following two major issues associated with cpp programs:

  • When a program is terminated, the entire data is lost.
  • If you have to enter a large number of data, it will take a lot of time to enter them all in
  • the different programs.

Suggest a solution and elaborate the same with the help of suitable examples. 


1
Expert's answer
2021-04-12T20:16:03-0400

The best solution will be to write data to a file.

For example like this:

#include <iostream>
#include <fstream>
#include <vector>


using namespace std;


int main()
{
    fstream fs;
    string buf = "";
    vector<string> names;
    int i = 0;
    int n;
    cout << "Enter the number of names in your file: ";
    cin >> n;
    fs.open("names.txt", fstream::out);
    if(fs.is_open())
    {
        i = 0;
        while(i < n)
        {
            cout << "Enter the " << i + 1 << "name: ";
            cin >> buf;
            fs << buf << "\n";
            if (buf.size() > 0)
            {
                names.push_back(buf);
            }
            i++;
        }
    }
    else
    {
        cout << "Can't open the file!";
        exit(0);
    }








    while (i < n);


    cout << "Your data: " << endl;
    for (i = 0; i < n; i++) {
        cout << names[i] << endl;
    }


    return 0;
}

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
APPROVED BY CLIENTS