简体   繁体   中英

My code will not read and display data from a file using ifstream and ofstream

While my data is put into the file named based on the user's input of "myfile", when I go to read and display it in the else statement, the name shows up as "", the balance is 0, and the file data is deleted.

We just learned fstream and its commands in my C++ class yesterday. Still new to using it. The teacher said that using getline(inputfile, name) and inputfile >> balance should read the data.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{

string myfile;
int balance = 0;
string name;

cout << "Enter your first name." << endl;
getline (cin, myfile);

ifstream inputfile(myfile);
ofstream outputfile(myfile);

if ( ! inputfile.good() )
{
        cout << "Enter your FIRST and LAST name." << endl;
        getline(cin, name);
        outputfile << name << endl;
        cout << "Hello " << name << endl;

        cout << "Enter your initial balance." << endl;
        cin >> balance;
        outputfile << balance << endl;
}
else
{
        getline(inputfile, name);
        cout << "Welcome Back" << name << endl;
        cout << "Here is a log of all your BALANCE activity." << endl;

       inputfile >> balance;
       cout << "Your balance is " << balance << endl;
}

outputfile.close();
inputfile.close();

return 0;
}

it should read the data from the file and display the full name as well as the balance integer value.

The computer is doing exactly what you told it to do.

getline (cin, myfile);

Get some text from the user and store it in myFile .

ifstream inputfile(myfile);

Open the file named by myFile for reading (if it exists).

ofstream outputfile(myfile);

Open the same file you just opened, but this time for writing. If the file exists, destroy its contents. If the file does not exist, create it.

Then you proceed to the if statement. If the file had existed, you proceed to the else clause. There you discover that the contents of the file have been destroyed. Not a surprise, since that is the default behavior when ofstream opens an existing file.

What you probably want to do is move the declaration of outputfile into the if statement so that it is only hit when the file does not exist.

if ( ! inputfile.good() )
{
        ofstream outputfile(myfile);

        cout << "Enter your FIRST and LAST name." << endl;
        getline(cin, name);
        outputfile << name << endl;
        cout << "Hello " << name << endl;

        cout << "Enter your initial balance." << endl;
        cin >> balance;
        outputfile << balance << endl;
        // No need to explicitly close the file, as the destructor will handle that.
}
else
{
    // etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM