为什么我的输入验证功能不起作用? (C++)

Why is my input validation function not working? (C++)

我正在编写一个程序,根据用户输入计算购买成本。如果用户对价格和数量使用负值或其他无效值,程序应打印错误并再次询问。

#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" 有一个 space 和一个字母字符,所以 str.find_first_not_of() 应该 return 5. 因此我在 validatePrice() 中的 if 条件应该计算为 false,不? 这个问题的第二部分是 validateQuantity() 被调用,即使控制台应该在等待我先输入数量。只有当我搞砸价格时才会发生这种情况。

对我的代码的任何其他修改(最佳实践、简化)将不胜感激。

std::cin << string 默认读取到第一个空格。请注意,如果您在 validatePrice() 中打印 str,它不会是您指定的完整输入。

您应该使用 std::getline() 来阅读整行。