istream& read(istream& in, vector<double>& input) {
if (in) {
//clear vector
input.clear();
double x;
while (in>>x) {
input.push_back(x);
}
in.clear();
}
return in;
}
int main () {
cout<<"please enter your golf scores:"<<endl;
vector<double> golf;
read(cin, golf);
cout<<"please enter your minigolf scores"<<endl;
vector<double> minigolf;
/*as per many online resources i've tried the following code to fix the problem
* but i i haven't had any success
* cin.clear();
* std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
* cin.ignore(); */
string x;
cin>>x;
return 0;
}
I've since read the problem may be exclusive to OSX. As i trawled google i stumbled upon this post:
Control-D is absolutely the way to send EOF. Looking at the error codes on cin, clear is doing its job, but when you call cin again, it looks at stdin and finds that it is still at the end of the file.
This behavior is different then what we find under Linux, but I'm not sure which one I'd call wrong. The clear() function is just resetting the bit - it doesn't change the state of stdin. Clearly, under Linux, Control-D just sends the EOF character, while on the mac it is actually closing stdin. I think both are equally valid interpretations of what "sending EOF" means.
The basic scenario is something like this. You want the user to enter a list of numbers terminated by a CTRL-D. But then you want to get the user's name or other data. On Linux this works, on Mac OS X the stream is closed down. The reality is you can't really use the CTRL-D approach in this way on Mac OS X.
Can anyone confirm that the stream cannot be reopened on osx? It seems strange.
In this function the state of the istream never goes bad or fails unless you input something that cannot be turned into a double. If you type a character at the end of your golf scores the istream goes bad. See then if it is cleared by this function.
If it is cleared you will still need to eat the '\n' left in the stream using whatever method you want in main().
1 2 3 4 5 6 7 8 9 10 11 12
istream& read(istream& in, vector<double>& input) {
if (in) {
//clear vector
input.clear();
double x;
while (in>>x) {
input.push_back(x);
}
in.clear();
}
return in;
}
Clearly, under Linux, Control-D just sends the EOF character, while on the mac it is actually closing stdin
There is no such thing as "EOF character" (except in CP/M and, by extension, MS Windows, but that's only relevant when opening binary files in text mode). There is "end of file" state. C streams (such as stdin) maintain their own state flags, C++ streams (such as std::cin) maintain their own.
Looking at the error codes on cin, clear is doing its job, but when you call cin again, it looks at stdin and finds that it is still at the end of the file.
But this part sounds right. Clearing cin's eofbit doesn't clear stdin's eofbit. Give clearerr(stdin) a try (but, in general, once the standard input is closed with ^D, there shouldn't be a use case to reopen it)