2014-04-12 3 views
0

나는 합계 가격에 가격을 추가하고 체크 아웃 할 준비가되었을 때 최종 합계를 제공하는 프로그램을 만들어야합니다.쇼핑 계산기

나는 총을 잘 처리하는 프로그램을 작성했지만 어딘가에 내 루핑 작업을 망쳤다 고 생각하고 체크 아웃하지 않기를 선택한 후 cin.get의 특정 인스턴스를 건너 뜁니다.

"체크 아웃 하시겠습니까?"대신 "프레스 q를 종료"하고 싶지만 문제를 예상하지는 않습니다.

내 입력 코드를 건너 뛰지 않도록 코드 수정 방법에 대한 아이디어가 있습니까?

#include <iomanip> 
#include <iostream> 

using namespace std; 
const int MAXCHAR = 101; 

int main() 
{ 
    double itemPrice = 0; 
    double totalPrice = 0; 
    char itemName[MAXCHAR]; 
    char confirm; 
    char checkoutConfirm; 
    char reply; 
    bool checkout = false; 


    while (checkout == false) 
    { 
     cout << "Enter Item Name(100 characters or less): "; 
     cin.get(itemName, MAXCHAR, '\n'); 
     cin.ignore(100, '\n'); 

     cout << "Enter Item Price: "; 
     cin >> itemPrice; 
     while(!cin) 
     { 
      cin.clear(); 
      cin.ignore(100, '\n'); 
      cout << "Invalid Input. Enter Item Price: \n\n"; 
      cin >> itemPrice; 
     } 
     cout << "Your entry:" << endl; 
     cout << itemName << " - $" << itemPrice << "\n"; 
     cout << "Correct?(y/n): "; 
     cin >> confirm; 

     if (confirm == 'y' || confirm == 'Y') 
     { 
      totalPrice += itemPrice; 
      cout << "Your total is: " << totalPrice; 
      cout << "Would you like to check out?(y/n): "; 
      cin >> checkoutConfirm; 
      if (checkoutConfirm == 'y' || checkoutConfirm == 'Y') 
      checkout = true; 
      else if (checkoutConfirm == 'n' || checkoutConfirm == 'N') 
      checkout = false; 
      else 
      { 
       cout << "Invalid Input. Enter y to checkout or n to keep shopping: "; 
       cin >> checkoutConfirm; 
      } 
     } 
     else if (confirm == 'n' || confirm == 'N') 
     { 
      cout << "Entry deleted -- Enter new information: \n"; 
     } 
     else 
     { 
      cout << "Invalid Input. Enter y to checkout or n to keep shopping: "; 
      cin >> confirm; 
     }   
    } 
    return 0; 
} 
+0

이 http://isocpp.org/wiki/faq/input-output#stream-input-failure에서 ISOCPP FAQ를 읽으십시오. –

답변

1

지우기 다시 사용하기 전에 입력 스트림 버퍼 : http://www.cplusplus.com/reference/ios/ios/clear/

std::cin >> x; 
std::cin.ignore(); 
std::cin.clear(); 

http://www.cplusplus.com/reference/istream/istream/ignore/ 그렇지 않으면 당신의 입력 버퍼에 남아있을 수 다시 사용됩니다. 내가 볼 수있는 한, 당신은 이미 그것을 종종 잊어 버렸지 만, 때때로 그렇게했습니다.

또한 종료 절차와 관련하여 this 질문을 살펴보십시오.