C ++如何检查输入float变量的有效输入 [英] C++ How to check an input float variable for valid input

查看:332
本文介绍了C ++如何检查输入float变量的有效输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个充当计算器的程序;基于用户输入的字符,它执行某一操作。程序的结构似乎工作正常,但我想能够检查错误的输入。在接收到float变量后,是否有任何方法来检查它是否不包含除数字和小数之外的任何字符?我尝试了 isdigit ,并且:

I'm writing a program that acts as a calculator; based on the character input by the user it performs a certain operation. The structure of the program seems to work fine, but I'd like to be able to check for erroneous input. After receiving the float variable, is there any way to check if it does not contain any characters other than digits and decimals? I've tried isdigit, and this:

if (!(cin >> x)) {
    cout << "You did not enter a correct number!" << endl; 
    return;
}

但似乎没有任何效果。

这里是我使用的一个简单操作函数的示例:

Here is a sample of one of the simple operation functions I'm using:

void Add(){
    float x = 0, y = 0, z = 0;
    cout << "Please enter two numbers you wish "
         << "to add separated by a white space:" << endl; 
    cin >> x >> y;
    z = x+y;
    cout << x << " + " << y << " = " << z << "." << endl;
    return;
}


推荐答案

你希望有一个数字,C ++不会自动知道你想要什么,所以一个解决方案是首先接受你的输入作为字符串,验证这些字符串,然后如果有效,只有使用atof()函数将字符串转换为浮点数。

To detect erroneous string input where you expected a number, C++ doesn't automatically know what you want, so one solution is to first accept your input as strings, validate those strings, then if valid, only then convert the strings to float numbers using the atof() function.

标准字符串类有一个名为find_first_not_of()的函数,可帮助您告诉C ++您认为有效的字符。如果函数发现一个字符不在你的列表中,它将返回坏字符的位置,否则返回string :: npos。

The standard string class has a function called find_first_not_of() to help you tell C++ which characters you consider valid. If the function finds a character not in your list, it will return the position of the bad character, otherwise string::npos is returned.

// add.cpp

#include <iostream>
#include <string>
#include <cstdlib>    // for atof()

using namespace std;


void Add()
{
    cout << "Please enter two numbers you wish "
         << "to add, separated by a white space:"
         << endl;

    string num1, num2;

    cin >> num1;
    if( num1.find_first_not_of("1234567890.-") != string::npos )
    {
        cout << "invalid number: " << num1 << endl;
        return;
    }

    cin >> num2;
    if( num2.find_first_not_of("1234567890.-") != string::npos )
    {
        cout << "invalid number: " << num2 << endl;
        return;
    }

    float x = 0, y = 0, z = 0;
    x = atof( num1.c_str() );
    y = atof( num2.c_str() );
    z = x+y;

    cout << x << " + " << y << " = " << z << "." << endl;
}

int main(void)
{
    Add();
    return 0;
}

这篇关于C ++如何检查输入float变量的有效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆