How to define a variable that might be a number or a word?

if an input might be either a number or a word, in case of a number it's value should be assigned to an int variable for mathematical operations. while in case of a word, it should be assigned to a string variable for taking decisions. How should I define that variable?
or is there a way I could store an input in 2 variables of 2 different definitions?
or assign the value of a number stored in a string variable to an int variable?
You could try reading it as an integer, and if it fails you try again reading it as a word.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int number;
if (std::cin >> number)
{
	// Do something with number.
}
else
{
	std::cin.clear(); // clear error flags so that you can try reading from it again.
	std::string word;
	if (std::cin >> word)
	{
		// Do something with word.
	}
	else
	{
		// Error!
	}
}
that was so helpful!
thank you very much :)
Topic archived. No new replies allowed.