-3

Suppose my string is "g9". I want my check to indicate that the string doesn't contain a number. However if my string is "123" or "-123", it should indicate that it's a number and it should return that string.

Minh Tran
  • 494
  • 7
  • 17
  • "g9" **does** contain a number 9 – Spikatrix Nov 09 '14 at 06:35
  • I think he means none are digits. Use std::none_of and std::isdigit. – prestokeys Nov 09 '14 at 06:36
  • `char *endptr; strtol(test_string, 10, &endptr); if (test_string == endptr || *endptr) Bad_Input();` – chux - Reinstate Monica Nov 09 '14 at 06:47
  • What code have you tried so far? – Soren Nov 09 '14 at 06:47
  • What do you want as the verdict if the string is `0xA` or `9e1`? They're hexadecimal and floating point numbers. What about 98765432109876543210? It's a valid decimal integer, but larger than fits in a 64-bit integer. You might want to investigate `strtol()` and `strtod()`, seeing whether they they use everything in the string when successfully converting it to a number. – Jonathan Leffler Nov 09 '14 at 06:58
  • @chux Sequence of argument of strtol is different. – BLUEPIXY Nov 09 '14 at 07:03
  • @BLUEPIXY Yes just saw that 2 minutes ago too. Should be `strtol(test_string, &endptr, 10);` – chux - Reinstate Monica Nov 09 '14 at 07:05
  • Sorry for the delayed response. I tried isdigit but it doesn't work with negative numbers. I also tried using strtok() to remove the negative sign before parsing but this gave me a seg error. It's possible that my implementation was ok and that it was another section of code that caused an error but this requires some testing, which is what I'm currently doing now. – Minh Tran Nov 09 '14 at 15:47
  • @prestokeys I think there is neither `std::none_of` nor `std::isdigit` in C... – glglgl Nov 23 '14 at 19:01

1 Answers1

3

This can be done at least in two ways:

  1. Using atoi function which parses string until first invalid character is encountered and returns integer number evaluated so far. Unfortunately, it provides almost no means for diagnostics.

  2. Better option is strtol which basically does the same thing, but returns pointer to first invalid character and sets errno if any error is encountered. Typical usage:

    #include <stdlib.h>
    ...
    const char* const numStr = "123";
    char* end;
    const long i = strtol(numStr, &end, 10);
    

    The end parameter allows you to check if the whole string was recognised as a valid number (in this case corresponding character is '\0'):

    const int ok = (*end == '\0' && end != numStr);
    

Follow provided links for examples and more info. Also, you may consider related functions in See also section.

Dmitrii Volosnykh
  • 1,165
  • 1
  • 12
  • 33