Creating and writing to a file

Hi, I'm new here, but sure could use some help. I'm trying to create a file, enter data and write the data to a file. I know I need to "write" the data to the file but not sure how to do that. My code is below. Should I use a cout function to do this? This is homework and I've read and reread the section on this, but still can't figure it out.

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream program3data;
outputFile.open("program3data.txt");

float num1, num2, num3, num4, num5;

cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the third number: ";
cin >> num3;
cout << "Enter the fourth number: ";
cin >> num4;
cout << "Enter the fifth number: ";
cin >> num5;

outputFile.close();
cout << "Done!\n";

return 0;
}
you should declare outputFile as ofstream and then you can use it as cout
eg:
1
2
3
4
5
//...
ofstream outputFile("program3data.txt");
//...
outputFile << "writing to file";
//... 


try to see if this web page could help you:
http://www.cplusplus.com/doc/tutorial/files.html
Last edited on
Going off of Bazzy's example, here is what your whole code would look like:


[code=cpp]#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ofstream outputFile;
outputFile.open("program3data.txt");

float num1, num2, num3, num4, num5;

cout << "Enter the first number: ";
cin >> num1;
outputFile << num1 << endl;
cout << "Enter the second number: ";
cin >> num2;
outputFile << num2 << endl;
cout << "Enter the third number: ";
cin >> num3;
outputFile << num3 << endl;
cout << "Enter the fourth number: ";
cin >> num4;
outputFile << num4 << endl;
cout << "Enter the fifth number: ";
cin >> num5;
outputFile << num5 << endl;

outputFile.close();
cout << "Done!\n";

return 0;
}[/code]

Happy to help,
CheesyBeefy :)
Last edited on
Topic archived. No new replies allowed.