我正在撰寫一個根據用戶輸入計算購買成本的程式。如果用戶對價格和數量使用負數或其他無效值,程式應列印錯誤并再次詢問。
#include <iostream>
#include <string>
#include <cmath>
#include <limits>
#include <algorithm>
using namespace std;
bool validatePrice(const string& str) {
if (str.find_first_not_of("0123456789.") != string::npos) {
return false;
} else if (stof(str) <= 0.0) {
return false;
} else {
return true;
}
}
bool validateQuantity(const string& str) {
if (all_of(str.begin(), str.end(), ::isdigit)) {
if (stoi(str) < 1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
int main() {
const float NYTAX = .0875;
string p;
string q;
float price = -1;
int quantity = -1;
float subTotal;
float total;
cout << "enter price: ";
while (price == -1) {
cin >> p;
if (!(validatePrice(p))) {
cout << "error, try a positive number.\n";
cout << "enter price: ";
} else {
price = stof(p);
}
}
cout << "enter quantity: ";
while (quantity == -1) {
cin >> q;
if (!(validateQuantity(q))) {
cout << "error, try a positive whole number.\n";
cout << "enter quantity: ";
} else {
quantity = stoi(q);
}
}
subTotal = price * quantity;
total = (round(subTotal (subTotal * NYTAX)) * 100) / 100;
cout << "Your total is " << total;
}
我的問題是雙重的。如果我輸入“3.00 d”作為價格,控制臺會列印:
enter quantity: error, try a positive whole number
enter quantity:
“3.00 d”有一個空格和一個字母字符,所以 str.find_first_not_of() 應該回傳 5。因此我在 validatePrice() 中的 if 條件應該評估為 false,不是嗎?這個問題的第二部分是呼叫 validateQuantity() 即使控制臺應該等待我先輸入數量。只有當我搞砸價格時才會發生這種情況。
對我的代碼的任何其他修改(最佳實踐,簡化)將不勝感激。
uj5u.com熱心網友回復:
std::cin << string默認情況下最多讀取第一個空格。請注意,如果您str在 inside列印validatePrice(),它將不是您指定的完整輸入。
您應該改為使用std::getline()來讀取整行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425388.html
上一篇:MySQL檢查一組屬性的唯一性?
