I am making a program to manage a text file. I have completed the program to add text, append and then read the text file, however when it comes to the inputs, using cout <<, cin >> string, only adds 1 word and not the full line of text entered. How can I add a full line of text. I worked out getline() works for reading from the file.
1 2 3 4 5 6 7 8 9 10 11 12
fstream file;
file.open("WriteTextFile.txt", ios::out);
file << UserInput << endl;
file.close();
cout << "Your file has now been written!\n";
Okay so I have this code now, however it does not ask for an input. so I included cin also, but with cid it will record all the data entered apart from the first word?
1 2 3 4 5 6 7 8 9 10 11 12 13
cout << "write text to a text file\n";
std::getline (std::cin, Input); //store input in string
fstream file; //declare file variable
file.open("WriteTextFile.txt", ios::out); //open file for input
file << Input; //add string content to file
file.close();
You haven't shown a full program, but from what you've shown it appears it should ask for input.
but with cid it will record all the data entered apart from the first word?
I don't understand what you mean by "apart from the first word"?
Are you reading in the first word elsewhere? The code you've shown should read in the entire first line.
My code is very big. this is the function I am trying to get to work. I'll will try and explain what happens. I run the function and it will output both couts and not ask for an input. That is what I meant by it not asking for an input. HOWEVER when I included cin to request and input and included getline under it, it would save the text from the cin ( ALL but the first word..so I enter hi babe sup..and it saves babe sup.) I hope this is more clear?
{
cout << "write text to a text file\n";
std::getline (std::cin, Input); //store input in string
fstream file; //declare file variable
file.open("WriteTextFile.txt", ios::out); //open file for input
file << Input; //add string content to file
file.close(); //close file
cout << "Your file has now been written!\n";
}
Thank you Furjoza. I did not ignore your post. Those are nice examples.
Do you have other inputs from cin that precede this code?
It's possible there is data (such as a \n) left in the cin buffer from a previous cin operation. This would cause the getline to terminate immediately. If this is the case, use cin.ignore http://www.cplusplus.com/reference/istream/istream/ignore/