how to use strtol with a char instead of a string whist comparing the char in an if statment

StackOverflow https://stackoverflow.com/questions/10172686

  •  31-05-2021
  •  | 
  •  

Domanda

I've spent a lot of time reading c tutorials and getting this code to compile/ work properly (as i suck at c) and I want to know what a cleaner/neater way of using a strtol would be instead of getchar(c) then changing c to an array chstr[] then using strtol on chstr.

Thanks Lachlan p.s. thanks to those that helped me with the isdigit checking

int main()
{
    char c;

    while((c = getchar()) !=EOF) {
        if (!check_chr(c)) {
            return 0;
        }
    }

    return 1;
}

int check_chr(char c)
{
    int a; char chstr[2];
    if (isdigit(c)) {
        chstr[0] = c; chstr[1] = "/0";
        a = (strtol(chstr,0,0));
        i = i + a;
        return 1;
    }

    if (c == ',')
        return 1;

    if (c == '\n')
        return 1;

    return 0;
}
È stato utile?

Soluzione

To convert a character holding a single digit into a binary number, just subtract the encoded form of '0'. This works since C guarantees that the character encoding has 0..9 in consecutive locations.

int digit_to_number(char c)
{
  if (isdigit(c))
    return c - '0';
  return -1;
}

This works because ín C, '0' is an int-typed (yes int, not char as you might expect) expression that evaluates to the value used to represent 0 in the target machine's encoding. For machines running e.g. ASCII or UTF-8 encodings natively, this value is (decimal) 48. For systems running EBCDIC, the value is (decimal) 240.

Using the character literal makes the translation of a character-digit into a number the compiler's problem, which is of course how it should be.

Altri suggerimenti

Well, you can parse the number manually. Something like that:

if (c >= '0' && c <= '9')
    number = c - '0';
else
    // error: c is not a decimal digit.

(put your error-handling code instead of comment)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top