cstrtol

why strtol returns zero?


im struggeling with a function. Goal is to check the user input (already sanitized) and act accordingly.

the function looks like this:

bool checkMove(board *Minesweeper,char *input){
  char *tmp;
  switch(input[0]){
    case '?':
      if(isalpha(input[1])){
        input[1]=toupper(input[1]);
        long eval = strtol(input, &tmp, 10);
        if(tmp==input){
          printf("something went wrong :(\n");
        }
        printf("Number: %ld\n",eval);

        if (eval>Minesweeper->height) {
          printf("Out of Bounds!\n");
        } else {
          printf("Valid move\n");
        }
// other stuff

The output:

Your Move: ?A21
something went wrong :(
Number: 0
Valid move

I'm passing the input values, so its not a local function. The same code (strtol) works in a different context just fine. I dont think its an issue with a local variable.


Solution

  • From the man pages:

    "The strtol() function converts the initial part of the string..."

    Your string starts with "?A", so the function fails. One solution would be to do the following instead:

    long eval = strtol(input+2, &tmp, 10);
    

    This way you "skip" the first 2 chars in input.