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.
#include <fstream>
#include <iostream>
#include <string>
usingnamespace 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;
}