我想知道的是,如果我要求用户输入内容,如果输入是整数或字符串或浮点值,我将如何输出.我想要一些方法来检查C++ 14中输入的数据类型.
例如.
如果输入是"Hello world"
输出应为:"输入为字符串"
如果输入为"134"
输出应为:"输入为整数"
如果输入是"133.23"
输出应为:"输入是浮动的"
读取字符串。
在中<string>,标准库提供了一组函数,用于从字符串或wstring的字符表示中提取数值。
使用x=stoi(s,p)。检查p-是否读取了整个字符串-它是整数。
用x=stof(s,p)或进行相同的操作x=stod(s,p),x=stold(s,p)以检查浮点/双精度/长双精度。
如果一切失败-它是字符串。
#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");
}
Run Code Online (Sandbox Code Playgroud)
预期输出:
It's a string: Hello world
It's an int: 134
It's a float: 133.23
Run Code Online (Sandbox Code Playgroud)