how would i stop a user from entering a letter when they should be entering a number?

#include <iostream>
      #include <cstdlib>
      #include <cstdio>
      #include <cstring>
     
      usin namespace std;

      int main(int nNumberofArgs, char* pszArgs[])

{
char nAns;

do{
  
     int nPly1;
     int nPly2;
     int nPly3;
     int nPly4;
     int nPly5;
     int nPly6;
     int nMandril;

cout<< "this program calculates an O.D. for you\n\n";

cout<< " enter seven numbers:\n\n";

cout<< " ply 1 if no ply enter 0-:";
cin>>nPly1;
cout<<\n;
cout<<" ply 2 if no ply enter 0-:";
cin>> nPly2;
cout<<\n;
cout<< "ply 3 if no ply enter 0-:";
cin>>nPly3;
cout<<\n;
cout<< " ply 4 if no ply enter 0-:";
cin>> nPly4;
cout<<\n;
cout<< "ply 5 if no ply enter 0-:";
cin>> nPly5;
cout<<\n;
cout<< "ply 6 if no ply enter 0-:";
cin>>nPly6;
cout<<\n;
cout<<"mandril -:";
cin>>nMandril;
cout<<\n;

cout<<"outside diameter = ";
cout<< (nPly1+nPly2+nPly3+nPly4+nPly5+nPly6)*2+nMandril;

cout<<" do you want to do this again? (y/n)";
cin>>nAns;

}while(nAns=='y'||nAns=='Y');

}

I would use getch() from conio.h.

For example :

#include <conio.h> // for getch()
#include <iostream>
using namespace std;

int main()
{

    int number=0;
    int help=0;
    char buffer=0;

    cout << "Type in any number : ";

    do
    {
        buffer = getch(); // reads the key from user
        help = buffer - '0';

        if (help >= 0 && help <= 9)
        {
            number *= 10;
            number += help;
            cout << help;
        }
        else
        {
            //cout << "\nERROR : No letters are allowed!";
        }

    }while(buffer != 13); // 13 = Return

    cout << "\nEntered number : " << number;

    getch();

    return 0;
}

Edited 4 Years Ago by Dman01: n/a

Dman01's suggestion only works on a select few compilers, therefore is not a good solution.

You need to read the input as a string of characters, test the characters to make sure they all all of the correct type, then either
1) show an error
2) convert to integer

> how would i stop a user from entering a letter when they should be entering a number?

There is no really portable way of doing that. What can be done is: let the user enter any set of characters, and if those do not form a valid number, ask for input again.

This may be all that you need:

int number ;
while( !( std::cout << "number? "  && std::cin  >> number ) )
{
    std::cin.clear() ;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;
}

With this, an input of 129XY would accepeted and treated as equivalent to 129. If 129XY is to be treated as invalid input, then validating the input as a string is required.

Use std::istringstream for this; it is easier than trying to validate it character by character yourself. 567, -567, +567 are all valid; 5-67, +-567, +5+67 are not.

int get_int()
{
    int number ;
    std::string str ;
    std::cout << "number? " && std::cin >> str ;
    std::istringstream stm(str) ;
    return stm >> number && stm.eof() ? number : get_int() ;
}

> how would i stop a user from entering a letter when they should be entering a number?

There is no really portable way of doing that. What can be done is: let the user enter any set of characters, and if those do not form a valid number, ask for input again.

This may be all that you need:

int number ;
while( !( std::cout << "number? "  && std::cin  >> number ) )
{
    std::cin.clear() ;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;
}

With this, an input of 129XY would accepeted and treated as equivalent to 129. If 129XY is to be treated as invalid input, then validating the input as a string is required.

Use std::istringstream for this; it is easier than trying to validate it character by character yourself. 567, -567, +567 are all valid; 5-67, +-567, +5+67 are not.

int get_int()
{
    int number ;
    std::string str ;
    std::cout << "number? " && std::cin >> str ;
    std::istringstream stm(str) ;
    return stm >> number && stm.eof() ? number : get_int() ;
}

being that i am new to programing i dont really know what all this means or where i would place this code, if you could explain a bit i would really appreciate it.

Hi,

I hope the below code will help you.

#include <iostream>
#include <unistd.h>

using namespace std;

int main( int argc , char **argv)
{

   char want;
   char *no;

   do {

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

      int len = strlen(no);
 
      int i=0;
      bool stat = true;

      while( i < len ) {
         if( isdigit((int)no[i]) ) {
            stat = true;
         } else {
            cout << "You have entered " << no[i] << ", this is not a number. so please type a number\n";
            stat = false;
            break;
         }
         i++;
      }

      if( stat == true ) {
        cout << "Yes you entered the input as numbers...\n";
      }

      cout << "do you still want to continue.. press 'y'";

      cin.clear();
      cin >> want;

   } while( want == 'y' );
}

Let me know, if you think its not correct.

BR/ KMat

how would i stop a user from entering a letter when they should be entering a number?

#include <iostream>
      #include <cstdlib>
      #include <cstdio>
      #include <cstring>
     
      usin namespace std;

      int main(int nNumberofArgs, char* pszArgs[])

{
char nAns;

do{
  
     int nPly1;
     int nPly2;
     int nPly3;
     int nPly4;
     int nPly5;
     int nPly6;
     int nMandril;

cout<< "this program calculates an O.D. for you\n\n";

cout<< " enter seven numbers:\n\n";

cout<< " ply 1 if no ply enter 0-:";
cin>>nPly1;
cout<<\n;
cout<<" ply 2 if no ply enter 0-:";
cin>> nPly2;
cout<<\n;
cout<< "ply 3 if no ply enter 0-:";
cin>>nPly3;
cout<<\n;
cout<< " ply 4 if no ply enter 0-:";
cin>> nPly4;
cout<<\n;
cout<< "ply 5 if no ply enter 0-:";
cin>> nPly5;
cout<<\n;
cout<< "ply 6 if no ply enter 0-:";
cin>>nPly6;
cout<<\n;
cout<<"mandril -:";
cin>>nMandril;
cout<<\n;

cout<<"outside diameter = ";
cout<< (nPly1+nPly2+nPly3+nPly4+nPly5+nPly6)*2+nMandril;

cout<<" do you want to do this again? (y/n)";
cin>>nAns;

}while(nAns=='y'||nAns=='Y');

}

Edited 4 Years Ago by Narue: Added code tags

Let me know, if you think its not correct.

It's not correct. Let's ignore that unistd.h isn't a standard header (you don't use anything from it anyway) and go right to the first real error. Boiled down, it looks like this:

char *no;

cin >> no;

int len = strlen(no);

First, you forgot to include <cstring> for strlen(). Second, you clearly don't understand how pointers work because an uninitialized pointer does not point to infinite memory. A pointer must be initialized to memory that your process owns before it can be used.

C++ is not just C with cin and cout, there are many more things that can make your life easier:

#include <algorithm>
#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    string line;
    
    while (true) {
        cout << "Enter a number (EOF to quit): ";
        
        if (!getline(cin, line))
            break;
        
        bool not_num = any_of(line.begin(), line.end(), [](char c) { return !isdigit(c); });
        
        cout << "'" << line << "' is" << (not_num ? " not " : " ") << "a number\n";
    }
}

Notice how you don't have to worry about pointers with the std::string class. That's one of the key benefits for people who are low level programming challenged. ;)

All of this is assuming that the need for a "number" means a series of digits rather than a value suitable for conversion to one of the integer or floating-point types. If you need to convert to a numeric type, the naive algorithm of "only allow digits" isn't sufficient as it rejects valid numbers and doesn't protect against numbers beyond the supported range.

Agree with narue's code !
Another modification that can be used, that is dman01's idea using getch()

#
#        \\include necessary headers
#

void main()
{clrscr();

 int i=0;
 char a[50];

 while(a[i]!='\r')  \\ reading carriage return(enter key)
   {a[i]=getch();
        
     if(isdigit(a[i])==0)
          {cout<<"You have entered a character, please enter only numbers";
            break;
           }
      ++i;
    }
}

The above program breaks from the loop if a character is entered.

Advantage : It tells the user at that instance whether he has given an incorrect input rather than after entering the whole string

Disadvantage : Not a very reusable code, may not work on all versions of c++

Agree with narue's code !
Another modification that can be used, that is dman01's idea using getch()

Advantage : It tells the user at that instance whether he has given an incorrect input rather than after entering the whole string

Disadvantage : Not a very reusable code, may not work on all versions of c++

Disadvantage : this is why we do NOT make this suggestion... It works on very few versions of C++.

Dude, get real... portability of a code IS a problem faced by every programmer.. And like i said, using dman01's idea... and on the version he uses, it IS possible.. And i can say that coz he used conio.h which isnt a part of the VC ++ library or the newer versions but instead for older versions like turbo c++. All the other codes also arent reusable if u think they are...

Only difference - I pointed it out !

This article has been dead for over six months. Start a new discussion instead.