Only the first word of a string is being written to file?

Sep 20, 2013 at 5:35pm
Hi all,

What I am trying to do is to get a string which is being assigned to by the cin command, and write it to a file. Now this is only working slightly. As the title says, the whole string is not being written to the file....only the first word:


1
2
3
4
5
6
7
8
9
10
11
12
13
string Text;
How I am writing to the file: 

 ofstream Write_Test("Write_Test.txt");//Creating the file
	//Write_Test.open("Write_Test");	//Opening it for writing to, the ios::trunc at the end means it will open the file if it already exists, and overwrite any existing data with the new data.		
	Write_Test << Text;					//Write a message to the file.
	Write_Test.close();					//Close the stream, meaning the file will be saved.		
	cout << "Done!";

What I am using to assign the value 'Text' which is what I am writing to the text file:

	cout << "Write something: ";
		cin >> Text;



Could anyone help me please?

Thanks
Sep 20, 2013 at 5:43pm
closed account (LzwkoG1T)
you need to use the following code to accept spaces in strings:

Write_test << getline( userString , cin );
Sep 20, 2013 at 5:52pm
It wont let me use getline? It is coming up with the red line underneath it:

Write_Test << getline( Text , cin );
Sep 20, 2013 at 6:03pm
Sep 20, 2013 at 6:08pm
Ok the error has gone away now, but when i open the file; instead of seeing what I just typed in, i see this:

5E85C288

Do you know why this is happenng?
Sep 20, 2013 at 6:20pm
Are you sure you aren't doing something silly like the following?

Write_Test << &Text;
Sep 20, 2013 at 6:25pm
Don't do this:
 
    Write_Test << getline(cin, Text);


Instead, try this:
1
2
    getline(cin, Text);
    Write_Test << Text;
Sep 20, 2013 at 7:45pm
Hi,

Sorry for the late reply.

That does not work unfortunately. What ia happening now is that it is writing everything after the first word?
Sep 20, 2013 at 7:53pm
Can you please show the latest version of your code.
Topic archived. No new replies allowed.