Read a line from file in C and extract the number of input

后端 未结 3 1681
感情败类
感情败类 2021-01-25 09:12

I have a file input.dat. In this file, there are 3 lines:

1 2 3
5 7 10 12
8 9 14 13 15 17

I am going to read one of the three li

3条回答
  •  难免孤独
    2021-01-25 09:32

    A bit cleaner version of chqrlie's answer. Started with a string as that is what the question is really about after fgets().

    sscanf() won't step through the string, it always reads from the beginning.

    strtol() looks for a long int in the beginning of the string, ignoring initial white-space. Gives back the address of where it stops scanning.

    The manual of strtol() says that errno should be checked for any conversion error.

    #include 
    #include 
    #include 
    
    #define STRING_SIZE 2000
    
    int main(void)
    {
        char line[STRING_SIZE] = "5 7 10 12";
    
        char* start = line;
        char* end;
    
        int count = 0;
    
        while(1)
        {
            /**
             * strtol() look for long int in beginning of the string
             * Ignores beginning whitespace
             * 
             * start: where to strtol() start looking for long int
             * end: where strtol() stops scanning for long int
             */
            errno = 0; // As strol() manual says
    
            strtol(start, &end, 0);
    
            if (errno != 0)
            {
                printf("Error in strtol() conversion.\n");
                exit(0);
            }
    
            if (start == end) break; // Quit loop
    
            start = end;
            count++;
        }
        
    
        printf("count: %d\n", count);
    
        return 0;
    }
    

提交回复
热议问题