Thursday, May 11, 2006

check for integer input in C++

The following source code could check whether your input is an integer:

#include <iostream>
#include <string>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
int main () {
     int n, ans;
     string instr;
     cout << "Enter an integer: ";
     cin >> instr;
     cout << instr.c_str() << endl;
     const char *c_instr = instr.c_str();
     for( int i=0; i<instr.length(); i++) { // check input
          if( !isnumber( c_instr ) ) {
               cout << "Input error: MUST be a positive integer.\n";
               exit(1);
          }
     }
     n = atoi( c_instr ); // convert to number
     ans = n + 1;
     cout << ans;
     return 0;
}

No comments: