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
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
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
>>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