Jake Wickham Jake Wickham - 4 months ago 9
C++ Question

when saving to file, words after white space are ignored

I've been working on saving to files and this was the result. The only problem is that anything after a space is ignored, (if you typed "john smith") it would print
("the last person to use this file was: john") I am using codeblocks with the GNU GCC compiler. Here is the code:

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main()
{
string name;
ofstream saveData;
ifstream Data;
Data.open("Info.data", ios::binary);
Data >> name;
Data.close();
cout << "The last person to use the file was " << name << endl;
cout << "What is your name?" << endl;
cin >> name;
saveData.open("Info.data", ios::binary);
saveData << name;
cout << name << endl;
system("PAUSE");
saveData.close();
return 0;
}


thanks

Answer

For strings objects of ifstream (including cin) use input from beginning till the first space, and space is SPACE, TAB, and NELINE. So, you should use getline instead cin >>

Try this:

Data.open("Info.data");
getline(Data, name);
Data.close();

and

cout << "What is your name?" << endl;
//cin >> name;
getline(cin, name);

UPDATE:

By the way, in your code after

   Data.open("Info.data", ios::binary);

you use

   Data >> name;

So, stream opened in binary mode is read by >> - it is not so good.