This code outputs words onto a text file only the first word disappears!!!what happened?

and how could i have the program outomaticly put .txt on the end of the filename without having to do it manually?




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 <iostream>
#include <string>
#include <fstream>

using namespace std;

main ()
{

string line;
string filename;


cout << "enter file name\n";
cin >> filename;
cin >> line;
ofstream myfile;
myfile.open  (filename.c_str());


getline(cin,line);
myfile << line;


return 0;
}
This code outputs words onto a text file only the first word disappears!!!what happened?
You are reading the first word on line 16 but don't do anything with it. Remove that line and it should work.

how could i have the program outomaticly put .txt on the end of the filename without having to do it manually?
filename += ".txt";
You should also have a myfile.close(); statement in there after you have finished using the file.

The system will usually automatically close any open files when the program exits, but it's good practice to explicitly close files. (Loss of data and other problems may occur when files aren't properly closed).
Last edited on
It's not necessary to close the file because the ofstream destructor will close the file if it's still open.
Last edited on
thats no good because if i get rid of line 16 then i cant input into the text file now can i.
i could bodge it and have the code pop in a first word automaticaly but that wouldnt solve the issue of haveing your first word dissapear
You do that on line 21.
how?
Topic archived. No new replies allowed.