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.
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";
}
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.
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.
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.
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