简体   繁体   English

"如何在 C++ 中检查输入是整数、字符串还是浮点数"

[英]How to check whether an input is integer, string or float in C++

What I want to know is, If I ask a user to input something, how will I output if the input is a Integer or String or a Float Value.我想知道的是,如果我要求用户输入一些东西,如果输入是整数、字符串或浮点值,我将如何输出。 I want some method to check the data type of the input in C++14.我想要一些方法来检查 C++14 中输入的数据类型。

For eg.例如。

If the input is "Hello world"如果输入是“Hello world”

Output should be : "The input is String"输出应该是:“输入是字符串”

If the input is "134"如果输入是“134”

Output should be : "The input is integer"输出应该是:“输入是整数”

If the input is "133.23"如果输入是“133.23”

Output should be : "The input is float"输出应为:“输入为浮点数”

Read string.读取字符串。

In <string><\/code> , the standard library provides a set of functions for extracting numeric values from their character representation in a string or wstring.<string><\/code>中,标准库提供了一组函数,用于从字符串或 wstring 中的字符表示中提取数值。

Use x=stoi(s,p)<\/code> .使用x=stoi(s,p)<\/code> 。 Check p<\/code> - if whole string was read - it is integer.检查p<\/code> - 如果整个字符串被读取 - 它是整数。

Do the same with x=stof(s,p)<\/code> or x=stod(s,p)<\/code> , x=stold(s,p)<\/code> to check for float\/double\/long double.x=stof(s,p)<\/code>或x=stod(s,p)<\/code> 、 x=stold(s,p)<\/code>执行相同操作以检查 float\/double\/long double。

If everything fails - it is string.如果一切都失败了 - 它是字符串。

"

The user will always input a string, what you can do is try to convert it to a float, if it succeeds then it probably is a float or an int.用户将始终输入一个字符串,您可以尝试将其转换为浮点数,如果成功则可能是浮点数或整数。 If the float conversion doesnt succeed then its probably not a number.如果浮点转换不成功,那么它可能不是数字。

"

#include <iostream>
#include <string>
#include <boost/variant.hpp>
#include <sstream>


using myvariant = boost::variant<int, float, std::string>;

struct emit : boost::static_visitor<void>
{
    void operator()(int i) const {
        std::cout << "It's an int: " << i << '\n';
    }

    void operator()(float f) const {
        std::cout << "It's a float: " << f << '\n';
    }

    void operator()(std::string const& s) const {
        std::cout << "It's a string: " << s << '\n';
    }
};

auto parse(const std::string& s) -> myvariant
{
    char* p = nullptr;

    auto i = std::strtol(s.data(), &p, 10);
    if (p == s.data() + s.size())
        return int(i);

    auto f = std::strtof(s.data(), &p);
    if (p == s.data() + s.size())
        return f;


    return s;
}

void test(const std::string& s)
{
    auto val = parse(s);
    boost::apply_visitor(emit(), val);
}

int main()
{
    test("Hello world");
    test("134");
    test("133.23");
}

The input is in a string.输入是一个字符串。 Without additional agreements, how could you possibly know if the user intended "1" to be the string containing the character '1' or a string representation of the integer 1?如果没有额外的约定,你怎么可能知道用户想要 "1" 是包含字符 '1' 的字符串还是整数 1 的字符串表示形式?

If you decide that "if it can be interpreted as an int, then it's an int. If it can be a double, then it's a double. Else it's a string", then you can just do a series of conversions until one works, or do some format checking, perhaps with a regexp.如果你决定“如果它可以被解释为一个 int,那么它就是一个 int。如果它可以是一个双精度,那么它就是一个双精度。否则它是一个字符串”,那么你可以只做一系列的转换,直到一个工作,或进行一些格式检查,也许使用正则表达式。

Since all ints can be converted into doubles, and string representations of doubles can be converted into ints (perhaps with some junk left over) if you care about the difference, you probably need to check for indicators of it being a double (digits with perhaps a . in it, possibly a 'e' with +\/- possibly after it. Etc. You can find regexps on the internet, depending on what you want to allow, leading +, e-notation, etc.由于所有整数都可以转换为双精度,并且如果您关心差异,则双精度的字符串表示可以转换为整数(可能还有一些垃圾),您可能需要检查它是否是双精度的指示符(数字可能一个 . 在其中,可能是一个“e”,后面可能有 +\/-。等等。您可以在 Internet 上找到正则表达式,具体取决于您要允许的内容、前导 +、电子符号等。

If it's an int, you can use regex ^\\d+$, else if it's a double, [+-]?(?:0|[1-9]\\d*)(?:.\\d*)?(?:[eE][+-]?\\d+)?如果是 int,则可以使用正则表达式 ^\\d+$,否则如果是 double,则 [+-]?(?:0|[1-9]\\d*)(?:.\\d*)?(? :[eE][+-]?\\d+)? else it's a string.否则它是一个字符串。

Here's some code that seems to work.这是一些似乎有效的代码。 :) :)

#include <iostream>
#include <string>
#include <regex>
using namespace std;


void handleDouble(double d) {
    std::cout << "Double = " << d << "\n";
}

void handleInt(int i) {
    std::cout << "Int = " << i << "\n";
}

void handleString(std::string const & s) {
    std::cout << "String = " << s << "\n";
}

void parse(std::string const& input) {
    static const std::regex doubleRegex{ R"([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)" };
    static const std::regex intRegex{ R"(\d+)"};

    if (std::regex_match(input, intRegex)){
        istringstream inputStream(input);
        int i;
        inputStream >> i;
        handleInt(i);
    }
    else if (std::regex_match(input, doubleRegex)) {
        istringstream inputStream(input);
        double d;
        inputStream >> d;
        handleDouble(d);
    }
    else {
        handleString(input);
    }
}

int main()
{
    parse("+4.234e10");
    parse("1");
    parse("1.0");
    parse("123abc");
}

You can easily wrap string.strof<\/code> for float<\/code> or string.stroi<\/code> for int<\/code> in try-catch block:您可以轻松地将string.strof<\/code>包装为float<\/code>或string.stroi<\/code>包装为int<\/code>在 try-catch 块中:

#include <string>
bool isFloat(string str) {
    try {
        float floatCheck = stof(str);
        return true;
    }
    catch (...) {
        return false;
    }
}

bool isInt(string str) {
    try {
        int intCheck = stoi(str);
        return true;
    }
    catch (...) {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM