如何检查输入的值是否为数字

How can you check if a value entered is numeric?

本文关键字:是否 数字 输入 何检查 检查      更新时间:2023-10-16
#include<iostream>
using namespace std;
int main()
{
    double money;
    cout << "Input the sum of money: ";
    cin >> money;
....

我一直在尝试检查输入的值是否是数值,以便在输入另一个值(字母)时显示错误消息,并且代码将循环回以再次要求输入(钱)

while ( ( cin >> money ) == false )
{
...
}

您可以在输入后检查流的状态。例如

if ( !( std::cin >> money ) ) std::cout << "Oh, I made a mistake!n";

如果你想重复输入,你应该调用

std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );

不要忘记包含标题<limits>