Hi please help me, im trying to make a program that only accepts numbers. What can I do to disable letters and special symbols? for example, I enter "sffsdttsfsjfs" / "!%#^$*$(" then the program would prompt that "Error: Letters and Special Symbols are not allowed"

I saw a thread here, but the solution is too complicated for me, a freshmen student, to understand, maybe theres a 1-5 line code for this? help me please

Recommended Answers

All 3 Replies

It's simple: Make sure that every character in the string given by the user is greater then or equal to '0' and less then or equal to '9'.

The reason this works is because each character in a string is really just represented by a number, and in ASCII (and practically any other encoding) the numbers 0-9 appear consecutively.

oh so thats why whenever i input a number it goes directly to the first condition in if/else. so what should i do? im not familiar yet with keywords, and i didnt get what you said in the first paragraph

Hi please help me, im trying to make a program that only accepts numbers ...

The presumption is that you are taking in a string
then validating that string to ensure it only contains
characters in the range '0'..'9'

You could use a function like this:

bool isNonNegInt( const string& test )
{
   // can test from back to front if desire ... //
   for( int i = test.size()-1; i >= 0; --i )
   {
      if( test[i] < '0' || test[i] > '9' )
         return false;
   }
   // if reach here, all passed, so can now ...
   return true;
}

You may also like to use these 3 handy utilites ...

string takeInString( const string& msg = "" )
{
    string val;
    cout << msg << flush;
    getline( cin, val );
    return val;
}
char takeInChr( const string& msg = "" )
{
    string reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChr( "More (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}

After all the includes needed, like:

#include <iostream>
#include <string>
#include <cctype> // re. to lower

and ...

using namespace std;

Then in main, you could code something like this ...

do
{
   string testVal = takeInString( "Enter a non negative integer: " );
   if( isNonNegInt( testVal ) )
      cout << "Good! You entered " << testVal << '\n';
   else
      cout << "NOT valid entry, try again ...\n";   
}
while( more() );
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.