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?
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.
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.
If it's an int, you can use regex ^\d+$, else if it's a 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");
}
output:
Double = 4.234e+10
Int = 1
Double = 1
String = 123abc