อาจซ้ำกัน:
ปัญหาในการใช้ cin สองครั้ง
รหัสนี้ใช้งานได้ แต่ไม่ใช่สิ่งที่ฉันตั้งใจไว้ ทุกครั้งที่ฉันต้องการป้อนเงินเดือนใหม่โดยการกด 1
ผลลัพธ์ที่ command prompt จะเป็นดังนี้:
Comic books : USD Input error! Salary must be in positive integer.
โค้ดควรหยุดที่ cout<<"\n\nComic books\t\t: USD ";
ที่บรรทัด 4 แต่เพิ่งดำเนินการโดยใช้ while loop ภายใน นี่คือรหัส:
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
และจะคำนวณเฉพาะอินพุตถัดไปเท่านั้น โปรดช่วยฉันด้วยเรื่องนี้ ขอบคุณล่วงหน้า.