Saving spaces in string (including file management)

What my program does is that the user (1) inputs a string, which is manipulated by the program, and subsequently (2) saved into a text file. The program should then (3) load the text file, read it and (4) load the text in the file back into the string for some further manipulation, and finally (5) print the whole string. The program works fine except for anything to do with reading, saving and printing spaces. I'm using fstream for the file management.

In the first two steps, it doesn't save the string into the text file past the first space.

I've tried a number of ways to solve this, such as getline (the logic behind which I have not quite yet understood), but it just ends up messing up the basic functions of the program. What I want to be able to do is simply to save the inputted string, along with any spaces it may contain, and then read the text file and print its contents.

Any help on this would be greatly appreciated. I realize I haven't attached any code to be analyzed, but I thought it would be easier to understand the core of the problem this way.
You need to verify what's in your string variable before you write its content to the file. Write it with std::cout so you can see what's in it.

It'll probably be the word without the space. In which case you need to double check how it reads the user input.
I can show you come code that "works" with some comments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string usr_string;
  cout << "Enter a string: ";
  getline(cin,usr_string); // gets string entered before user hits return
  fstream usr_text("input.txt",ios_base::out | ios_base::in); // declares file stream and opens it for reading and writing
  if(usr_text.good()) // make sure file was created ok
  {
    usr_text << usr_string << endl; // write string to file with linefeed
    usr_text.seekg(0,ios_base::beg); // set get pointer to beginning of the file
    getline(usr_text,string); // read contents of file back to string
    cout << endl << "You entered: " << usr_string << endl; // output string
  }
  return 0;
}
Thank you! Works perfectly.
Topic archived. No new replies allowed.