2014-12-09 1 views
-1

저는 고객의 누적 가격을 추적하는 장바구니 프로그램을 작성하는 과제를 작성했습니다.오류 검사 및 종료를 위해 루프하는 간단한 방법이 있습니까? (C-strings/Character Arrays)

문자열, 전역 변수 또는 사용자 정의 함수를 사용할 수 없습니다. 문자 배열과 루프 만 사용하도록 엄격히 명령 받았습니다.

장바구니 프로그램이 정상적으로 작동하는 동안 내 코드를 단순화 할 수있는 방법이 있는지 궁금합니다. 지나치게 복잡하게 코드를 작성한 것에 대해 불이익을받는 것처럼 느껴집니다. 내 종료 기능이 지나치게 복잡하다는 느낌이 든다. 문자열이나 함수를 사용하지 않고 구현하는 더 좋은 방법이 있습니까?

#include <iostream> 
#include <iomanip> 
#include <cmath> 

using namespace std; 


int main() 
{ 
char continueOrQuit; 
char productName[900]; 
float productPrice; 
float totalCost = 0; 
int productQuantity = 0; 
bool validResponse; 

cout << "Welcome to SmartCart" << endl; 
cout << "Simply enter the name of your product when prompted" << endl; 
cout << "After you enter your product, enter the price when prompted \n\n"; 

//while ((productName[900] != 'D', 'o', 'n', 'e') || (productName[900] != 'd', 'o', 'n', 'e')) 
//While im not done shopping 
do 
{ 

    cout << "Name of Product: "; // Prompt for product 
    cin.getline(productName, 900); // Get the name 
    cout << endl; 
    cout << "Cost of Product: "; // Prompt for product cost 
    cin >> productPrice; // Get the cost 
    while ((!cin) || (productPrice < 0)) 
    { 
     cout << "Invalid Input!! Try again!!" << endl << endl; 
     cout << "Cost of Product: "; // Prompt again for product cost 
     cin.clear(); 
     cin.ignore(100, '\n'); 
     cin >> productPrice; 
    } 
    cin.ignore(250, '\n'); // Ignore the rest of the garbage 
    cout << endl; 
    // if everything is correct, we set up the display and give the results. 

     cout.setf(ios::fixed, ios::floatfield); 
     cout.setf(ios::showpoint); 
     cout.precision(2); 
     cout << "The item(s) \"" << productName << "\" has/have been added to your cart for $" 
     << productPrice << endl; 
     totalCost = totalCost + productPrice; // Calculating the cumulative sum total 
     cout << "Your shopping total so far is: $" << totalCost << endl; // Display the sum total 
     productQuantity++; // Count the number of items in cart 
     cout << "You have " << productQuantity << " item(s) in your cart." << endl; 
     // Display the amount of characters in the cart 
     cout << "To quit shopping, type \"Q\". Otherwise, type \"C\" (Without quotation marks)" 
     << endl; 
     cout << "Would you like to continue shopping? (C/Q) : "; 
     cin >> continueOrQuit; 
     cin.ignore(100, '\n'); 
     continueOrQuit = tolower(continueOrQuit); 
     if (continueOrQuit == 'q') 
     { 
      cout << "You have chosen to finish and check out." << endl; 
      validResponse = true; 
     } 
     else if (continueOrQuit == 'c') 
      validResponse = true; 
     else 
      cout << "You have to type either C or Q!" << endl; 
      validResponse = false; 
      while (!validResponse) 
      { 
       cout << "Would you like to continue shopping? (C/Q) : "; 
       cin >> continueOrQuit; 
       cin.ignore(100, '\n'); 
       continueOrQuit = tolower(continueOrQuit); 

       if (continueOrQuit == 'q') 
       { 
        cout << "You have chosen to finish and check out." << endl; 
        validResponse = true; 
       } 
       else if (continueOrQuit == 'c') 
        validResponse = true; 
      } 
} while (continueOrQuit == 'c'); 

cout << "Your checkout total is $" << totalCost << endl; 
cout << "You are purchasing a total of " << productQuantity << endl; 
system("PAUSE"); 
return 0; 

} 코드의`여기

+0

알아두면, while 루프를 사용하려고했습니다. 그러나 while 루프는 내가 입력 한 것인지 아닌지 신경 쓰지 않는 것처럼 보입니다. 어쨌든 계속 될 것입니다. – user3505632

+0

'cin'이 닫히면 기존 while 루프가 무한 루프로 바뀝니다 (예 : 프로그램이 파일에서 파이프 된 입력으로 실행되고 파일의 끝에 도달 함) –

+0

죄송합니다. 코드를 다시 실행했습니다. 당신이 종료하기로 결정할 때 문제가 있습니다. 그것은 실제로 사용자가 종료하기를 원하기 전에 두 번 실행됩니다. – user3505632

답변

0

짧은 버전. 주로 입력을 검사 할 때 do while을 입력하여 여분의 코드를 제거했습니다. 잘못된 입력의 경우 다시 입력이 첫 번째 시도로 돌아갑니다.

마지막 괄호에 괄호가없는 경우 올바르게 입력 한 경우 q 또는 c를 다시 입력해야합니다.

여기 코드는 원본과 비교할 수 있습니다.

int main() 
{ 
    char continueOrQuit; 
    char productName[900]; 
    float productPrice; 
    float totalCost = 0; 
    int productQuantity = 0; 
    bool validResponse; 

    cout << "Welcome to SmartCart" << endl; 
    cout << "Simply enter the name of your product when prompted" << endl; 
    cout << "After you enter your product, enter the price when prompted \n\n"; 

    do 
    { 
     cout << "Name of Product: "; // Prompt for product 
     cin.getline(productName, 900); // Get the name 
     cout << endl; 
     do{ 
      cout << "Cost of Product: "; // Prompt for product cost 
      cin >> productPrice; // Get the cost 
      if(!cin || productPrice < 0){ 
       cout << "Invalid Input!! Try again!!" << endl << endl; 
       cin.clear(); 
       cin.ignore(100, '\n'); 
      } 
     }while ((!cin) || (productPrice < 0)); 

     cin.ignore(250, '\n'); // Ignore the rest of the garbage 
     cout << endl; 
     // if everything is correct, we set up the display and give the results. 

     cout.setf(ios::fixed, ios::floatfield); 
     cout.setf(ios::showpoint); 
     cout.precision(2); 
     cout << "The item(s) \"" << productName << "\" has/have been added to your cart for $" 
     << productPrice << endl; 
     totalCost = totalCost + productPrice; // Calculating the cumulative sum total 
     cout << "Your shopping total so far is: $" << totalCost << endl; // Display the sum total 
     productQuantity++; // Count the number of items in cart 
     cout << "You have " << productQuantity << " item(s) in your cart." << endl; 
     // Display the amount of characters in the cart 

     do{ 
      cout << "To quit shopping, type \"Q\". Otherwise, type \"C\" (Without quotation marks)" 
      << endl; 
      cout << "Would you like to continue shopping? (C/Q) : "; 
      cin >> continueOrQuit; 
      cin.ignore(100, '\n'); 
      continueOrQuit = tolower(continueOrQuit); 
      if(continueOrQuit == 'q' || continueOrQuit == 'c') 
       validResponse = true; 
      else 
      { 
       cout << "You have to type either C or Q!" << endl; 
       validResponse = false; 
      } 
     }while(!validResponse); 
     if (continueOrQuit == 'q') 
     { 
      cout << "You have chosen to finish and check out." << endl; 
     }  
    } while (continueOrQuit == 'c'); 

    cout << "Your checkout total is $" << totalCost << endl; 
    cout << "You are purchasing a total of " << productQuantity << endl; 
    system("PAUSE"); 
    return 0; 
} 
+0

정말 고마워요. 나는 때때로 "모호한"오류를 만들기 때문에 OR 사용에 주저했다. 그러나 이것은 코드를 확실히 수정했습니다. 불행히도 나는 사용자가 계속하고 싶어한다는 것을 나타 내기 위해 'c'를 얻을 수 없다. – user3505632

+0

왜 그럴까? c를 입력하면 어떻게됩니까? – SHR

+0

신경 쓰지 마라. 편집을 완전히 읽지 못했습니다. 나는 do 함수를 포함하지 않았다. 내가 그렇게했을 때 몇 가지 조정을해야했지만 훌륭하게 작동합니다. 솔루션에 대해 너무 고마워요. – user3505632

관련 문제