Jake Wickham Jake Wickham - 1 year ago 41
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;
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;
return 0;


Answer Source

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:

getline(Data, name);


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


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.