-
getline with File
I cant understand why the following code wont work. When it gets to the getline stage, it doesn't wait for the prompt.
I'm running it in Microsoft visual c++ Express and the .h file includes iostream and fstream
Code:
#include "file.h"
using namespace std;
int main()
{
string file_location;
string file_text;
cout << "Where would you like to store your file" ;
cin >> file_location;
cout << endl;
cout << "What would you like to write in your file";
getline(cin, file_text);
ofstream fout(file_location);
fout << file_text;
fout.close();
}
However, if i change the order around - I.E i move the getline and cin around as the code below demonstrates - it all checks out ok and works.
Code:
string file_location;
string file_text;
cout << "What would you like to write in your file";
getline(cin, file_text);
cout << endl;
cout << "Where would you like to store your file" ;
cin >> file_location;
ofstream fout(file_location);
fout << file_text;
fout.close();
-
cin >> will extract everything up to the first space. The rest gets left behind in the input buffer.
After that, getline will come and read it all.
Suggested solution: Use only getline.
And don't forget to include iostream and string.
Oh, and you don't need to call close on the streams.
-
The >> operator leaves white space AND newlines on the input stream.
So when the getline comes along (with it's newline only delimiter), it is immediately satisfied by the newline left behind.
This comes up regularly, search for cin.ignore()
-
It is not recommended to use cin >> for anything that has to do with paths (any space would screw up the input).
-
Thanks Elysia and Salem.
What would be best used for a path?
-