我正在製作一個程序,詢問用戶他們想要購買什麼商品以及每件商品的數量,然後計算所有商品的總金額。我想知道的是,我會如何確保爲「金額」輸入的輸入只是一個正數。我已經在這裏搜查,只發現了同類型C以外的問題語言++在C++中測試正數的輸入
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
//Constants for menu
const int
NOTEBOOK = 1, //Represents choice for notebook
PEN = 2, //Represents choice for pen
PENCIL = 3, //Represents choice for pencil
EXIT = 4; //Exits the program
//Constants for Prices
const double
NOTEPRICE = 1.50, //Represents notebook price
PENPRICE = .30, //Represents pen price
SPECPEN = .25, //Represents pen price when coupon code is entered
PENCILONE = .20, //Represents pencil price when 1-4 are purchased
PENCILFIVE = .15, //Represents pencil price when 5-9 are purchased
PENCILTEN = .10; //Represents pencil price what 10 or more are purchased
int
choice, //Represents what number choice the user selects
amount; //Represents the amount of the item selected that the user wants to purchase
double
totalPrice,
noteTotal = 0,
penTotal = 0,
pencilTotal = 0;
string
coupon;
do
{
//Display Menu
cout << "\tWelcome to Martin Office Supplies\n\n";
cout << "Our inventory\n\n";
cout << "1. Notebooks\n";
cout << "2. Pens\n";
cout << "3. Pencils\n";
cout << "4. Exit\n\n";
cout << "Please make a selection: ";
cin >> choice;
//Validates menu selection
while (choice < NOTEBOOK || choice > EXIT)
{
cout << "Sorry we dont sell that item.\n";
cout << "Please make another selection.\n";
cin >> choice;
}
//Responds to users menu selection
switch (choice)
{
case NOTEBOOK:
cout << "How many notebooks would you like to buy?";
cin >> amount;
noteTotal = amount * NOTEPRICE;
cout << "The subtotal for the notebook(s): " << noteTotal << endl << endl;
break;
case PEN:
cout << "How many pens would you like to buy? ";
cin >> amount;
cout << "Please type in a coupon code or NONE ";
cin >> coupon;
if (coupon == "pen123")
{
penTotal = SPECPEN * amount;
}
else
{
penTotal = PENPRICE * amount;
}
cout << "The subtotal for the pen(s): " << penTotal << endl << endl;
break;
case PENCIL:
cout << "How many pencils would you like to buy? ";
cin >> amount;
if (amount <= 4)
{
pencilTotal = PENCILONE * amount;
}
else if (amount >= 5)
{
pencilTotal = PENCILFIVE * amount;
}
else if (amount >= 10)
{
pencilTotal = PENCILTEN * amount;
}
cout << "The subtotal for the pencil(s): " << pencilTotal << endl << endl;
}
totalPrice = noteTotal + penTotal + pencilTotal;
cout << "Thank you for your order\n\n\n";
cout << "Your total is $ " << totalPrice << endl;
} while (choice != EXIT);
return 0;
}
1.閱讀一些字符串2.檢查字符串是否代表正整數 – MikeCAT
請將您的列表限制在與問題相關的部分代碼中。 –
你也可以使用無符號類型... –