• 0

[C++] Simple writing to file (using cout?)


Question

A quick question.

How would I go about very simply writing some data to an external file? Like a log for example.

Could it be done using cout?

It must be the simplest possible, my experience in C++ is zilch!

Cheers guys!!

Link to comment
Share on other sites

8 answers to this question

Recommended Posts

  • 0
at the open() method, you set the mode to "ios:out | ios::app"

e.g-

ofstream myfile;
myfile.open ("example.txt", ios::out | ios::app);

i believe this should solve your problem..

Indeed it does, you're a star!!

Thanks :D

Link to comment
Share on other sites

  • 0

#include <iostream>
#include <fstream>
using namespace std;

int main () {
	ofstream myfile ("C:\\temp\\datafile.txt", ios::app);
  if (myfile.is_open())
  {
	myfile << "I am Alpha and Omega.\n";
	myfile.close();
  }
  else cout << "Unable to open file";
  system("PAUSE");
  return 0;
}

How can I change the above code so that I can input anything (rather than a fixed line) from the executable itself (command prompt) to the text file?

Link to comment
Share on other sites

  • 0

#include <iostream>
#include <fstream>
using namespace std;

int main () {

	//Take a number as input (change the type as necessary)
	int myNumber;
	cout << "Enter a number: ";
	cin >> myNumber;

	//Open the file
	ofstream myfile ("C:\\temp\\datafile.txt", ios::app);


	//Check if the file is open, and add the number the user input to it if it is open
	if (myfile.is_open())
	{
		myfile << myNumber;
		myfile.close();
	}
	else
	{
		cout << "Unable to open file";
	}

	//Wait for the user to hit enter before exiting the program
	system("PAUSE");

	//Exit the program
	return 0;
}

Not that this code doesn't check the input, so the program will crash if you don't input a proper number.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.