hi,

OVer the last few days, I've bee having serious issues trying to check input from the user and making sure its numeric, I recently found this function like many others but I cannot get it to work.

#include <cstdlib>
#include <iostream>

using namespace std;

bool IsNumeric(const char *p)
{
  for ( ; *p; p++)
    if (*p < '0' || *p > '9')
      return false;
  return true;
}

int main(int argc, char *argv[])
{
    
    int sInput = "";

    cout << "Please provide in input: ";
    
    cin >> sInput;
    
    cout << endl << endl << IsNumeric(sInput);
    
    cout << endl << endl;
    
    system("pause");
    return 0;
    
}

See I have a integer variable and want to make sure the user doesnt input a alphabetic character or string. Any advice would be great, also I've developed in php and vb which had a great IsNumeric function but c++ doesnt have one I beleive.

17 C:\Documents and Settings\Walkers\Desktop\C++\Is Numeric\main.cpp invalid conversion from `const char*' to `int'

In vb, I would overcome this using Cstr() but with c++ I'm lost.

Edit: I want to be able to use a function like this so I can just perform an IF statement expecting a boolean true or false return.

Recommended Answers

All 6 Replies

You are setting an integer variable to "", which is a string, thus a char*. You could probably use ' ' but why initialize it to anything?

sInput should be a char*

What u could do is declaring the sinput as follows:

char sinput[20];

This should resolve the issue.

and what about different base numbers?
Right now it will reject valid hexadecimal input (for example) while accepting invalid octal and binary input.

Member Avatar for iamthwee

and what about different base numbers?
Right now it will reject valid hexadecimal input (for example) while accepting invalid octal and binary input.

My guess is he doesn't care about numbers with a different bases.

(*p < '0' || *p > '9')

What about floating numbers? I.e. where does your decimal point go?

And if it does contain a decimal point is it legal, i.e is there only one etc...

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.