I am reading the book 'Accelerated C++', and I am unable to reproduce the results for their read homework problem even after exactly copying their code on my machine. The basic problem is about using cin.clear() to change the failure state of the inpute stream after the use of EOF to indicate that all the grades have been entered. Authors suggest Ctrl+D on linux systems for EOF. I already saw this and this but they couldn't solve my problem.
Here is my minimal working example:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string name, city;
vector<double> homework;
cout << "Enter your name : " ;
cin >> name;
cout << "Hello " + name + "!" << endl;
cout << endl;
cout << "Enter your grades" << endl;
if (cin)
{
homework.clear();
double x;
while (cin >> x)
{
homework.push_back(x);
}
cin.clear();
}
cout << endl;
cout << "Enter your city : " ;
cin >> city ;
cout << "You live in " + city << endl;;
return 0;
}
After entering all the homework, I hit Ctrl+D and then I expect that I would now be given chance to enter city name. But the program just ends after printing the two strings at the end of my code. What is wrong with my understanding of cin.clear()
? I would also like to point out that using cin.ignore()
after cin.clear()
doesn't help either.