variable type?

Jul 22, 2012 at 11:10am
Hello,
I've started C++ programming not more than a couple of days ago... and there is a question I cannot find any answer to on the web, so I thoght of posting my question on a forum: does anyone know how one can test the type of a variable? For example, I'd like the user to enter un integer, and I was thinking of doing a while(type(number)!=integer) I know it's wrong but is there any solution? Thank you in advance.
Jul 22, 2012 at 11:16am
The type is fixed at compile time. If you declared number to be an int you know that it will always be an int.

EDIT:
When reading from a stream (like std::cin) you can put the read operation inside the loop condition to check that the read was successful. If you try to read an int and the user enters a letter the loop will stop.
1
2
3
4
5
int number;
while (std::cin >> number)
{
	std::cout << "You have entered number " << number << ".\n";
}
Last edited on Jul 22, 2012 at 11:21am
Jul 22, 2012 at 11:23am
Yes but if the user enters "tree" when I ask them a, it doesn't work! Same problem if the number is a "double" or a negative number. I use for the moment: while (a<0 ) { cout <<"a? "; cin>> a; } but I wondered if I could do the same thing if a was a string or a double... not an int.
Jul 22, 2012 at 11:24am
See my EDIT above.
Jul 22, 2012 at 11:32am
I just started c++ like 2 weeks ago so im no guru either...but im thinking if u want a response then it might be better to use #include string before the main function. I think i had a similar problem when working on a program that was shutting down if the wrong 'data' was typed in. Using the string function, I was able to make the program flawless for a whole lot more characters...unless im not getting ur question right.
Jul 22, 2012 at 11:32am
you can try to do something with unions.
but then also you have to get an input and test conditions.
Jul 22, 2012 at 11:40am
See, you can read double and check if the fractional part is zero. If so, you have entered an integer value. For example:
1
2
3
4
5
6
double number, fracpart, intpart;
while(cin>>number)
{
fracpart=modf(number, &intpart);
if(fracpart==0.)break;
}

And do not forget to #include<cmath> .
I know this is not what you want, but I hope it helps you.
Other people could provide you more elegant solution.
Jul 23, 2012 at 8:57am
Thank you all for the replies. Honestly it still isn't what I looked for, but it doesn't matter. I've tested another example of program on the Web to see if other programmers did anything to prevent this problem: so I entered "fetefg" (just a string variable...) and there was a bug: a non-stop loop :)
I just let drop...
Thank you all the same
Topic archived. No new replies allowed.