1

Hi could someone point me out what's wrong with this code ?

#include <stdio.h>
int convstrg(char* str) {
   int output = 0;
   char* p = str;
   for (int i=0;str[i]!='\0';i++) {
      char c = *p++;
      if (c < '0' || c > '9')
        continue;
      output *= 10;
      output += c - '0';
   }   
   return output;
}

int main(){
    char x[] = "1xx23";
    printf("%d\n", convstrg(x));
    return 0;
}

The code should return an integer when the output is string integer. But it seems i getting weird number such as 0.

this are few test case, some of it works some didn't

"123" -> 123
"23xyz" -> 23
"" -> 0
"abc" -> 0
"-1" -> -1

Thanks

EDIT

Ok now i sort out all the cases expect for negative string..

d3bug3r
  • 2,492
  • 3
  • 34
  • 74
  • @icabod problems is negative numbers for "-1" i get 1 in return – d3bug3r Sep 27 '13 at 08:12
  • 1
    You have no logic for handling negative values - you'll need to add that. But since this is C++ why are you even re-inventing the wheel like this (and using C-stye coding) when there are much better alternatives that require no coding? – Paul R Sep 27 '13 at 08:12
  • @novavent: Yeah, just saw that it wouldn't work for the negative, so deleted my comment :) – icabod Sep 27 '13 at 08:14

1 Answers1

2
  • You are never checking to see if the leading character is - thus you can not expect to have negative numbers parsed correctly.
  • You should break if (c < '0' || c > '9') instead of continue. Otherwise the parsed value from 12xyz123 will be very strange.
  • I hope you know there are built-in functions for parsing an integer from a string for instance using std::atoi or using a std::stringstream. Have a look here for more details.
  • You can also use third-party library like boost::lexical_cast like so boost::lexical_cast<int>(x)
Community
  • 1
  • 1
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • i would like todo without using build in function – d3bug3r Sep 27 '13 at 08:26
  • @novavent that is why I added also errors I found in your code. Still it is good to have all options in the answer as your question never stated you want to do it without using built-in functions. – Ivaylo Strandjev Sep 27 '13 at 08:28
  • "12xyz123" this case actually return a correct answers, look at here http://codepad.org/41KhzOrP – d3bug3r Sep 27 '13 at 08:29
  • @novavent I don't think this is the correct value for parsing 12xyz123, but that's your call. I believe you should either return 0 indicating that the parsing failed or only return 123. – Ivaylo Strandjev Sep 27 '13 at 08:30