954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Writing information to a file

Good day, everyone.

I am refreshing my c++ skills from a year break or so :$

I am having some troubles remembering on how to write to a file. I have the general idea down, but I am not sure what I am doing wrong. I would be much appreciative if anyone can help me figure this out.

(by the way I am using Netbeans IDE 6.8)

Here is my code: (the red text is where the trouble is)

/*
 * Program to let user login and logout.
 * User's information will be put into a separate .txt file called "loginfo.txt"
 */

#include <stdlib.h>
#include <iostream>
#include <fstream>

using namespace std;

struct LogIn
{
    string username;
    string password;
};

void menu();
// displays the menu and double checks if the .txt file is empty or not
// to ensure if there are any previous users registered in the program

int main()
{
    menu();
    
    return 0;
}

void menu()
{
    LogIn log;  // declaring a struct object

    int choice = 1;

    fstream loginfo; // file declared
    loginfo.open("loginfo.txt"); // opening txt file

    if(loginfo.eof())
        exit(0);

    //making sure the user inputs the correct
    while (choice == 1 || choice == 2)
    {
        cout << "~~~~~~~~~~~~~~~~~~\n"
             << "~SHOP CENTER PLUS~\n"
             << "~~~~~~~~~~~~~~~~~~\n\n";

        cout << "Would you like to:\n"
             << "1. Log in\n"
             << "2. Register (NEW USERS ONLY)\n"
             << "3. Exit\n"
             << "?> ";

        cin >> choice;

        if(choice == 1)
        {
            bool isEmpty = loginfo.peek() == EOF;

            if(isEmpty == true)
                cout << "\nERROR: No one is registered in the system\n"
                     << "Please go back and register as a new user.\n\n\n";

            else
            {
                //section is "under construction"
                cout << "\nUsername: ";
                cin >> log.username;
                cout << "\nPassword: ";
                cin >> log.password;
            }
        }

        else if (choice == 2)
        {
            cout << "Please set the following for your Log In information:\n"
                 << "\nUsername: ";
            cin.ignore();
            getline(cin, log.username);
            loginfo << log.username; // not sure why this isn't displaying in txt file

            cout << "\nPassword: ";
            getline(cin, log.password);
            loginfo << log.password;
        }

        else if(choice == 3)
        {
            cout << "\nHave a good day.\n\n\n";
            exit(0);
        }
        
        else
            cout << "\nInvalid input. Please try again.\n\n";
    }
}
strwbry.coder
Newbie Poster
5 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

well i figured it out. i just needed to add the endl after each like so:

loginfo << log.username << endl;
loginfo << log.password << endl;


*sigh* just that simple i suppose.

The next obstacle is for me to figure out how to add another registered user without having it make a fit that the file is "empty" as well as not even writing the new information in the file (it always keeps the old one there in the file).

Toodles for now. Until I have another issue with this program I am practicing on ^_^'

strwbry.coder
Newbie Poster
5 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

You have to use ofstream, not just fstream.

else if (choice == 2)
        {
	  ofstream outfile; // file declared
	  outfile.open("output.txt"); // opening txt file
            cout << "Please set the following for your Log In information:\n"
                 << "\nUsername: ";
            cin.ignore();
            getline(cin, log.username);
            outfile << log.username << std::endl; // not sure why this isn't displaying in txt file
            cout << log.username << std::endl; // not sure why this isn't displaying in txt file

            cout << "\nPassword: ";
            getline(cin, log.password);
            outfile << log.password << std::endl;
	    cout << log.password << std::endl;
	    outfile.close();
        }


Maybe someone knows how to do it using fstream, but this is how I would do it.

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

Create a class Users having objects "userName" & "passWord" & use funtions to write into a file in binary using read() & write(). It should be a cake walk.

nbaztec
Posting Pro in Training
475 posts since May 2010
Reputation Points: 57
Solved Threads: 60
 
You have to use ofstream, not just fstream. Maybe someone knows how to do it using fstream, but this is how I would do it.


fstream provides an interface for both reading(ifstream) and writing(ofstream). Nothing wrong with OPs method.

nbaztec
Posting Pro in Training
475 posts since May 2010
Reputation Points: 57
Solved Threads: 60
 

Except that it didn't work!! No output file was produced for me when I declared ouutfile as an fstream. As soon as I changed it to ofstream it worked as expected. Can you explain that behavior to us?

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 
Except that it didn't work!!


Didn't Notice that. Did you open it. using ios::open?

fstream file;
file.open("abc.txt",ios::out);

I've used this in past without any problem.

nbaztec
Posting Pro in Training
475 posts since May 2010
Reputation Points: 57
Solved Threads: 60
 

This behaves as expected:

#include <cstdlib>
#include <iostream>
#include <fstream>

int main()
{
  std::fstream file;
  file.open("abc.txt",std::ios::out);
  file << "some text";
  file.close();
  
  return 0;
}


This does not produce a file:

#include <cstdlib>
#include <iostream>
#include <fstream>

int main()
{
  std::fstream file;
  
  file.open("abc.txt");
  file << "some text";
  file.close();
  
  return 0;
}


Interesting.

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

daviddoria and nbaztec, thank you very much for your responses!

I totally forgot about the read() and write() functions that can be created! Definitely a cakewalk indeed!

Thanks for the good information gentlemen!

strwbry.coder
Newbie Poster
5 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

This behaves as expected:

#include <cstdlib>
#include <iostream>
#include <fstream>

int main()
{
  std::fstream file;
  file.open("abc.txt",std::ios::out);
  file << "some text";
  file.close();
  
  return 0;
}

This does not produce a file:

#include <cstdlib>
#include <iostream>
#include <fstream>

int main()
{
  std::fstream file;
  
  file.open("abc.txt");
  file << "some text";
  file.close();
  
  return 0;
}

Interesting.

Dave


Dear Dave,
In the earlier one, you are opening the file in output mode(ios::out) while in the latter in the absence of any flags it takes deafault read mode(ios::in), hence your issue.
ofstream & ifstream are dedicated streams so they don't require any flags while opening a stream connection. Whereas the fstream object serves for both ifstream & ofstream hence you need to explicitly define the mode as a flag (ios::out/ios::in/ios::app/ios::binary).
Hope this clears up things.

nbaztec
Posting Pro in Training
475 posts since May 2010
Reputation Points: 57
Solved Threads: 60
 

>>You have to use ofstream, not just fstream

fstream inherits from ifstream and ofstream, so it can do both, read and write.

firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: