Sending output to the cout stream, or an equivalent file stream, is easy and predictable, but using input streams like cin is more difficult because the contents of the stream are unpredictable. Attempting to read letters into an int, for example, will cause an error, and reading in a string containing spaces is difficult.
A good way of reading a stream is to read whole lines as strings (which always works), and then translate them into numbers as appropriate:
string linein; vector<string> lines; ifstream myfile("test.txt") // this loop will terminate at the end of the file while (getline(myfile, linein)) { lines.push_back(linein); } // Additionally, you can stop when a special line is seen: while (getline(myfile, linein) && linein !="END") {... // And then, either within the while loop or later: int myint = atoi(mystring.c_str()); double mydbl = atof(mystring.c_str());
The functions atoi() ("ascii to integer") etc. ignore trailing characters that they do not understand, and return zero if the input is hopeless:
atoi("2.995e2foo") is 2 atof("2.995e2foo") is 299.5 atof("bogus") is 0.0
These functions require a C-style string rather than a C++ string; hence the need for the c_str() function of the strings above. They are in <cstdlib>.
Alternatively, catch any errors that occur and handle them on the spot:
cout << "I'll accept an int -> "; if (cin >> i) { cout << "That was " << i << endl; cin.ignore(INT_MAX, '\n'); // skip junk to end of line } else { cout << "Nope" << endl; cin.clear(); // clear the error cin.ignore(INT_MAX, '\n'); // skip everything to end of line }