Create .txt files in c++

Jan 25, 2011 at 6:45pm
I need to make a program that gives you the chance to write what you want and then it saves it in .txt.
But all I got so far is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("NotepadExample.txt");
  if (myfile.is_open())
  {
    myfile << "This is a text example, this text will be saved in .txt format."<<endl;
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}


This program makes a .txt file with the sentence written on myfile << "This is a text example, this text will be saved in .txt format."<<endl;
but what I'm trying to do is that the program asks you to write something and that "something" will be saved in a .txt format.
Any ideas?
Last edited on Jan 25, 2011 at 6:45pm
Jan 25, 2011 at 6:50pm
Don't double post... so just use a string to store user input and then output that string to your text file.
Jan 25, 2011 at 6:51pm
Use cin + string's getline and write the strings in a loop to the file.

1
2
3
4
5
6
7
std::string str;
while ( std::getline( std::cin, str ) )
{
  if (str == "exit")
    break;
  myfile << str;
}
Jan 25, 2011 at 6:57pm
wolfgang__

sorry I can't understand can you post the code you just posted in the whole code? I don't know where it goes, sorry but i'm a beginner.
Jan 25, 2011 at 7:17pm
Just look at it and try to fit it, Alex cpp. Just by looking at that snippet, you can tell myfile has to be an open file, so the snippet must fit somewhere between ofstream myfile ("NotepadExample.txt"); and myfile.close();.
Jan 25, 2011 at 8:01pm
I've managed to do it in an easyer way, thanks to all!
Topic archived. No new replies allowed.