Help with string input AND output to file

I'm trying to write a simple program that will prompt for a string typed in by keyboard and save it to a file. I've tried lots of variations and this is just the latest version. Would appreciate corrections for a total newbie.

//Prompt for a string input by keyboard and save it to a file

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

int main()
{
string line;
ifstream myfile;
myfile.open ("newtext.txt");
string input = "";
cout << "Input text and press return:\n";
getline(cin, input);
//cout << getline (cin, input);
//cin i;
myfile << getline(cin, input); //error here
myfile.close();
return 0;
}
Please use code tags next time.
http://www.cplusplus.com/articles/z13hAqkS/

You were very close.
ifstream is for reading files or Input.
ofstream is for output files.
remember I for in and O for out.

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

int main()
{
string line;
ofstream myfile; // Error was here
myfile.open ("newtext.txt");

string input = "";
cout << "Input text and press return:\n";
getline (cin, input); // Error was here
myfile << input; // Error was here

myfile.close();
return 0;
}
Last edited on
Thought I was doing both: input from the keyboard, output to the file. Think I'm too new to know which is meant when -- from the C++ viewpoint. In any case, thanks much for the fix. Works great.
Topic archived. No new replies allowed.