<分区>
例如,我如何检查此字符串中的值是否为 double
:
string a = "1.55"
或int
:
string b = "2"
或“字符”
string c = "b"
标签 c++
<分区>
例如,我如何检查此字符串中的值是否为 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
关于c++ - 如何检查字符串中值的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594442/