Jump to content

Validity of input

- - - - -

  • Please log in to reply
2 replies to this topic

#1
hbk

hbk

    Learning Programmer

  • Members
  • PipPipPip
  • 71 posts
How can I check in c++ if a string or character was entered in an integer field.

Exg.

Enter a number:
user enters: a

I want the program to output an error message.

#2
mnirahd

mnirahd

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 330 posts
Hi,

you must take the input into a character array. Then through a loop check all the characters in the array are between '0' && '9'. Try it, and let us know how does it go.

Munir

#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
You may use the ctype functions in ctype.h header to check input, a small example:
#include <iostream>
#include <ctype.h>
using namespace std;

int main ()
{
    unsigned char myinput;
    cin >> myinput;
  
    if(!isdigit(myinput)) {
        cout << "Please enter an integer.\n";
    }
    
    return 0;
}

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users