如何检查字符串中值的数据类型

How check the data type of a value in a string?

本文关键字:数据类型 字符串 何检查 检查      更新时间:2023-10-16

例如,如何检查此字符串中的值是否为double:

string a = "1.55"

int:

string b = "2"

或"字符"

string c = "b"

这里最大的问题是您的需求太模糊,因为数据类型和字符串表示之间没有1:1的映射

比如"2"呢?它可能是double,也可能是int,甚至是char !更糟糕的是,double值2.0很可能表示为"2"而不是"2.0"

那么前导字符和尾随字符呢?"2.0 "是否为有效的double ?"2.0x"呢?"2.0 x"?

所以我们必须用一个反问题来回答你的问题:你将如何处理从字符串中收集到的类型信息?或者更准确地说,你想要解决的真正问题是什么?

无论如何,我不认为正则表达式在其中起任何作用。字符串流看起来是一种很有前途的方法。模式总是或多或少地尝试转换字符串,如果失败则说明字符串没有正确的格式。一个字符串可以表示不止一种类型,所以你必须选择哪一种优先。

为了更严格一些,您可以检查是否使用了整个输入字符串进行转换。下面是一个完整的玩具示例,具有描述性名称:

#include <sstream>
#include <string>
#include <iostream>
#include <vector>
template <class T>
bool CanBeUsedToCreate(std::string const &string_representation)
{
    std::istringstream is(string_representation);
    T test_object;
    is >> test_object;
    bool const conversion_successful = !is.fail();
    bool const whole_string_used_for_conversion = is.rdbuf()->in_avail() == 0;
    return conversion_successful && whole_string_used_for_conversion;
}
int main()
{
    std::vector<std::string> test_strings;
    test_strings.push_back("x");
    test_strings.push_back("2");
    test_strings.push_back("2.0");
    for (std::vector<std::string>::const_iterator iter = test_strings.begin();
        iter != test_strings.end(); ++iter)
    {
        std::cout << """ << *iter << "" as double? " << (CanBeUsedToCreate<double>(*iter) ? "yes" : "no") << "n";
        std::cout << """ << *iter << "" as int? " << (CanBeUsedToCreate<int>(*iter) ? "yes" : "no") << "n";
        std::cout << """ << *iter << "" as char? " << (CanBeUsedToCreate<char>(*iter) ? "yes" : "no") << "n";
    }
}
输出:

"x" as double? no
"x" as int? no
"x" as char? yes
"2" as double? yes
"2" as int? yes
"2" as char? yes
"2.0" as double? yes
"2.0" as int? no
"2.0" as char? no

遍历字符串。检查isalpha如果字符串包含char否则找到.,如果找到,它是double(如果最后一个字符不是f)否则int

基于C++11的解决方案:
#include <iostream>
#include <string>
#include <cstdlib>
#include <stdexcept>
int main (int argc, char * argv [])
{
    std::string x = argv [1];
    size_t pos = 0;
    bool isOk = true;
    try {
        stoi (x, & pos);
    }
    catch (std::invalid_argument) {
        isOk = false;
    }
    if ( (pos == x.length () ) && isOk) {
        std::cout << "Integer." << std::endl;
    }
    else {
        isOk = true;
        try {
            stod (x, & pos);
        }
        catch (std::invalid_argument) {
            isOk = false;
        }
        if ( (pos == x.length () ) && isOk) {
            std::cout << "Double." << std::endl;
        }
        else {
            std::cout << "String." << std::endl;
        }
    }
    return EXIT_SUCCESS;
}
输出:

$ ./program 21  
Integer.  
$ ./program 21.22  
Double.  
$ ./program 21.22. 
String.  
$ ./program 21.22ddd  
String.  
$ ./program x21.22  
String.