how can i check my data types?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main()
{
   int num;
   int mul;

   cout << "Enter a number: ";
   cout >> num;
   
   //if()
   
   mul= num*10;
   cout << "This is 10 times the numbers << mul << endl;

   /*   
   else
   {
      cout << "Input error, Please try again."
      return main();
    }*/

   return 0;
 


this is the simple program i wrote, an d i want to know is there anyway to check my data type of num so that the program will only run when user enter an integer value. it will prompt "Input error, Please try again." when user enter a float, string or char values, can someone help me, i have no idea how to do that....
The condition you are looking for is if(cin):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
{
   int num;
   int mul;

   cout << "Enter a number: ";
   cin >> num;

   if(cin)
   {
       mul= num*10;
       cout << "This is 10 times the numbers " << mul << '\n';
   }
   else
   {
      cout << "Input error, bye\n";
      return 1;
   }
   return 0;
}


demo: http://ideone.com/uA2oB

PS If you want to loop back and try again, you will have to clear the error and dispose of the unprocessed input (the type of num is int, nothing else can be written to num, so non-numbers remain unprocessed)

PS/2: float input will not be rejected, because cin >> num will see the digits up to the decimal point as a valid integer. If you want to reject floats, go with hamsterman's link.
Last edited on
O.O wow! clever job! i'm impress! thx you so much ^^
can i know is there a way to empty the stdin buffer to remove the non-int data?
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); will remove one line from stdin. Here numberic_limits comes from <limits> header and could be replaced with any big number. If you want to remove all chars up to the first digit, I guess you could while (is_not_a_digit(cin.peek())) cin.ignore();
Last edited on
Topic archived. No new replies allowed.