输入浮点数而不是整数时出现 C++ 输入错误

C++ Input errors when entering a floating point instead of integer

我正在尝试为 class 写一些东西,这基本上是一个小型在线商店。这个想法是显示一定数量的库存,询问用户 he/she 想要多少,并在他们完成后显示购物车。我拥有我需要的一切并且它运行完美,除非用户说他们想要一个浮点数的东西。
我们应该检查所有输入是否有错误,并继续询问用户,直到输入正确的输入。我所知道的任何条目(我知道)由字母和数字组成,但是当输入小数时,它会向下舍入到最接近的整数,将其用于当前项目,然后跳到下一个输入机会(下一项)并立即在那里给出错误消息。

void printError(int stock, int &numberOfCopies){
        cin.clear();
        cin.ignore(INT_MAX, '\n');
        cout << "Invalid amount" << endl << "Enter a number from 0 - " << stock ><< ": ";
        cin >> numberOfCopies;
}

int getQuantity(string title, int stock){
    int numberOfCopies;
    cin >> numberOfCopies;
    while (cin.fail() || numberOfCopies < 0 || numberOfCopies > stock){
        printError(stock, numberOfCopies);
    }
        if (numberOfCopies == 1){
            cout << endl << numberOfCopies << " copy of " << title << " has been >added to your cart" << endl;
        }
        else if (numberOfCopies > 1 && numberOfCopies <= stock){
            cout << endl << numberOfCopies << " copies of " << title << " have >been added to your cart" << endl;
        }
        else if (numberOfCopies == 0){
            cout << "You did not change your cart" << endl;
        }
    return numberOfCopies;
}
int numberOfCopies1 = getQuantity(title1, stock1);

这是我现在必须检查的错误(title1 和 stock1 是预定义的)。我正在使用 cin.fail() 检查不是整数的值,但在输入小数时它不起作用。
我在这里忽略了什么?

when a decimal is entered, it rounds down to the nearest integer, uses that for the current item, then skips to the next input chance (the next item) and immediately gives an error message

这就是流的工作方式,因此它们可用于解析 int 后跟任何其他分隔符或内容的内容。如果你想把它当作一个错误——检查没有尾随的垃圾——你应该使用 std::getline,之后通常很方便构造一个 std::istringstream 从中获取 int,检查此后没有垃圾:

std::string line;
while (getline(std::cin, line))
{
    std::istringstream iss(line);
    if (line >> n >> std::ws && iss.eof())
        break;
    ...clear/ignore/prompt again...
}

当提示输入单个整数时,getline / istringstream 舞蹈匹配您可以从 std::cin 获得的输入量 - 如果您直接使用 std::cin >> n >> std::ws && std::cin.eof(),它仅当 std::cin 命中 EOF 时才会失败 - 例如用户在 UNIX/Linux 主机上键入 Control-D,在 Windows 上键入 Control-Z 等,之后他们可能无法输入更多文本(取决于确切的 OS) .

请注意,流式传输到 floatdouble 然后检查它等于 floor 本身将解决您报告的确切问题,但是如果有人输入其他废话“ 27x", "27O", 你仍然会提取前导整数部分并让其余部分在下次触发错误报告....