Hi all,
I have a QUESTION regarding data validation

I'm writing a program, where i want the input to be only integers.
so if they enter things such as letters or symbols it won't crash my program.

i tried stuff like,

while(inputArray[count] != int)
cout << "Invalid Input. Please enter a integer." << endl;
cin >> input;

Is this possible? since letters are essentially also integers?

Thank you.

Enter the data as a string or get them from the keyboard one character at a time and check each character. You can use the macro isdigit() for that purpose.

Sure you can -

int main( void )
    int  thing_i;
    char thing_c;

    std::cout<< typeid( thing_i ).name() << '\n';
    std::cout<< typeid( thing_c ).name() << '\n';

    if ( typeid( thing_i ) == typeid( thing_c ) )
        std::cout<< "Both types the same!";
        std::cout<< "Types are of different types. Phooey!";

    return 0;

Oh. I misinterpreted what you meant.

You could use stringstreams I guess. They're great. Or isdigit() or any of those issomething()'s.

I'll definitly give those a try .


>Is this possible?
Yes. When you pass cin an integer type, it tries to read and format an integer. If the string it reads isn't a valid integer, it'll fail. You can use that to validate the input and try again:

#include <iostream>
#include <ios>     // For streamsize
#include <limits> // For numeric_limits


int x;

while ( !( cin>> x ) ) {
  cerr<<"Invalid input detected\n";

  // Clean up the mess by discarding the entire line
  cin.ignore ( numeric_limits<streamsize>::max(), '\n' );

You can also read a string without formatting it and manually validate, but because the acceptable formats of different types aren't always simple, it's better to leave validation to libraries that are carefully designed and tested.

>since letters are essentially also integers?
All input comes in the form of a stream of characters. Does that mean you can't use anything but characters in your program? Of course not. You can convert those characters into any representation you'd like. Just because a character is a small int doesn't mean you aren't able to differentiate between letters and digits. For example:

int jsw_atoi ( const string& s )
  int result = 0;

  for ( string::size_type i = 0; i < s.size(); i++ ) {
    // Convert the character to its numeric representation
    int digit = s[i] - '0';

    // Make room for the new digit
    result *= 10;

    // Attach the new digit
    result += digit;

  return result;

Narue -- I apologize for erroneously editing your post -- intended to hit Reply W/Quote and hit the edit button instead. So now your post is nonsense.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.