how to tokenize string to array of int in c?

前端 未结 6 1597
暖寄归人
暖寄归人 2020-12-15 01:01

Anyone got anything about reading a sequential number from text file per line and parsing it to an array in C?

What I have in a file:

12 3 45 6 7 8
3         


        
6条回答
  •  無奈伤痛
    2020-12-15 01:40

    Use strtol() to parse each line:

    #include 
    #include 
    #include 
    
    int main(void)
    {
        static char buffer[1024];
        static long values[256];
    
        while(fgets(buffer, sizeof buffer, stdin))
        {
            char *current = buffer;
            size_t i = 0;
            while(*current && *current != '\n' &&
                i < sizeof values / sizeof *values)
            {
                char *tail = NULL;
                errno = 0;
                values[i] = strtol(current, &tail, 0);
    
                if(errno || tail == current)
                {
                    fprintf(stderr, "failed to parse %s\n", current);
                    break;
                }
    
                ++i, current = tail;
            }
    
            // process values
            printf("read %i values\n", i);
        }
    }
    

提交回复
热议问题