0

I want to check if my array has only numbers how can I check it out?

i try this example but this not working and i dont Understand why.

int main() {

char* str = new char[9];
cin >> str;




cout << isdigit(str[0])<<endl;


system("pause");
return 0;
}

input:

1234

output: 4

what i want is:

input: 1234

print: ok

input:
12fg

print: not ok (because the character in my array)

I look forward to your help and explanation

thank's.

david
  • 15
  • 6
  • `isdigit` returns: _"Non-zero value if the character is a numeric character, zero otherwise."_ so you need to write a bit of code. – Richard Critten Mar 30 '17 at 20:05
  • why would you expect it to print 'ok'. isdigit returns either 0 or not 0 to indicate that something is a digit – pm100 Mar 30 '17 at 20:05

2 Answers2

1

try this

if(isdigit(str[0]))
  cout << 'ok'
else
  cout << 'not ok'

extra credit 1. Using this validate the whole string

extra credit 2. Find a different way to verify the whole string (there are many)

extra credit 3. Harder, find out why you got '4' from isdigit(str[0])

pm100
  • 48,078
  • 23
  • 82
  • 145
1

Try something like this:

const char *s = "1234";

while (isdigit(*s)) s++;
const char *result = (*s) ? "not ok" : "ok";
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • IMHO thats way to fancy for such a beginner question. Took me a while to work out what its doing, I mean its clever but really obscures the basic logic – pm100 Mar 30 '17 at 20:14