Writing strings to a .txt file

I have the following code:

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


string input(void)
{
    string in;
    
    cout << "What do you want to put in the text file?\n";
    cin >> in;
    return (in);
}


int main()
{
    string prompt = input();
    ofstream myfile;
    myfile.open("This_is_generated_by_a_C++_program");
    myfile << prompt;
    myfile.close();
    cout << "\nText successfully written to the file";
    return 0;
}


It works, however, when I tested it and tried to write "Testing my code!" to the file, it only wrote
Testing
in the file. How do I make it write the entire string to the file, instead of just the characters before the space?

Any help is appreciated! Thanks.


EDIT: Typo fix
Last edited on
use getline instead of >> on line 12
cin >> in; reads until entering space. getline(cin, in); reads til end of line
Thanks! It works now!
Topic archived. No new replies allowed.