Possible Duplicate:
Problem of using cin twice
This code works but not what I intended. Every time I want to enter new salary by pressing 1
the the output at command prompt will become like this:
Comic books : USD Input error! Salary must be in positive integer.
The code should stop at cout<<"\n\nComic books\t\t: USD ";
at line 4 but it just executed with the inner while loop. This is the code:
double multiplePay =0;
cout<<"\n\nEnter employee pay for each job";
while (1){
cout<<"\n\nComic books\t\t: USD ";
//cin.get(); if enable, the first user input will be 0. this is not working.
std::string comic_string;
double comic_double;
while (std::getline(std::cin, comic_string))
{
std::stringstream ss(comic_string); // check for integer value
if (ss >> comic_double)
{
if (ss.eof())
{ // Success so get out
break;
}
}
std::cout << "Input error! Salary must be in positive integer.\n" << std::endl;
cout<<"Employee salary\t: ";
}
comic = strtod(comic_string.c_str(), NULL);
multiplePay = comic + multiplePay; // update previous salary with new user input
cout << multiplePay;
cout << "Add other pay?"; // add new salary again?
int y;
cin >> y;
if (y == 1){
cout << multiplePay;
}
else{
break;
}
} // while
cout << multiplePay; //the sum of all salary
Using cin.get()
will solve the problem but the first user salary input will become 0
and only the next input will be calculated. Help me with this please. Thanks in advance.