Search code examples
cstringio-redirectionstrtol

strtol c string function


I'm using input via redirection. I'm trying to store numbers from a string to an integer.

The first number is 1989... however only '1' gets stored. Am I using strtol wrong?

table is an array of structs

value is an array of integers.

//(*row, i, j) = 0

while((c = fgetc(stdin)) != EOF)
{
    if (c != ' ' && c != '\n')
    {
        str[i] = c;
        i++;
    }

    else if (c == ' ')
    {
        str[i] = '\0';
        i = 0;
        table[*row].value[j] = strtol(str, NULL, strlen(str));

This code works and it does go into the else if after it reads in 1989... but for some reason strtol is only storing '1' instead of storing '1989'.


Solution

  • Yes you are using it wrong. The last argument is the base of the number to parse. For normal decimal numbers that should be 10. See e.g. this reference.