Reputation:
I'm new to c++ coming from a python background.
If I want input from a user and then I want to check what data type the input is (e.g. integer or float), how is it possible for me to declare the variable that I want to assign the user's input to?
Upvotes: 10
Views: 4439
Reputation: 12817
Short answer: You can't.
Long answer: You can't. C++ is a statically typed language, meaning that you have to define the type at compile time. Python is dynamically typed, so the type of an object can change from line to line.
If you want to get some input from the user though, you can just use a string though.
For example, if you want to get integer input from the user:
int n;
std::cin >> n;
Float input:
float x;
std::cin >> x;
And so forth. Do note in those two cases, if the user inputs something other than an integer or float, you'll have to check the flags of std::cin to see if there was an error.
But you need to tell the user "Input integer now" or "Input float now". You can't just accept some arbitrary type. Instead, design your code so you have alternative code paths for either integer or floating point input. Or force one or the other, and print an error when they give the wrong type of input.
Don't write your code like you're in Python. Idiomatic Python code is not idiomatic C++ code, and the way you accomplish things will not look the same.
In C++ the way to get arbitrary input would look like:
std::string input;
std::cin >> input;
if (IsInteger(input))
{
// do stuff with integer
}
else if (IsFloat(input))
{
// do stuff with float
}
else
{
std::cout << "Bad Input!" << std::endl;
}
Edit: As MSalters pointed out in a comment, You can actually use boost::lexical_cast<T>(expr)
to cast a string representation to some type T (Where T is usually something like int, float, double, etc). Do note, you'll probably still have to do some checking to see if expr
is actually an integer, float, or otherwise.
Upvotes: 22
Reputation: 1365
Python is dynamically typed language and on the contrary, c/c++ are statically typed languages. It is not possible to find the the type and declare at run time.
Upvotes: 1
Reputation: 69958
C++ is a statically typed language. All the variable types must be known at compilation time.
Upvotes: 1
Reputation: 65466
Much better to collect a string from the user and then parse it.
This question is the place to look for an answer: How to parse an int from a string
Upvotes: 3
Reputation: 992707
When you get input from the user, it will arrive as a string
. For example:
std::string inp;
std::cin >> inp;
Then, you take the contents of inp
(which is whatever the user typed), and look inside it to see what characters it contains. At that point you could make decisions based on whether it contains (a) all digits, (b) digits and a decimal point, or (c) something else entirely.
Upvotes: 5