可能重复:
两次使用 cin 的问题
这段代码有效,但不是我想要的。每次我想通过1
在命令提示符下按输出来输入新工资时,都会变成这样:
Comic books : USD Input error! Salary must be in positive integer.
代码应该在第 4 行停止,cout<<"\n\nComic books\t\t: USD ";
但它只是使用内部 while 循环执行。这是代码:
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
使用cin.get()
会解决问题,但是第一个用户的薪水输入会变成0
并且只计算下一个输入。请帮帮我。提前致谢。