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

后端 未结 3 1655
感情败类
感情败类 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:53

    the loop while (sscanf(line, "%d ", &number)) keeps parsing the first number in the line.

    You should use strtol instead:

    #include 
    #include 
    
    #define STRING_SIZE 2000
    
    int main() {
        FILE *fp = fopen("in.dat", "r");
        char line[STRING_SIZE];
        int lcount = 0, nline = 1;
    
        if (fp != NULL) {
            while (fgets(line, STRING_SIZE, fp) != NULL) {
                if (lcount == nline) {
                    char *p = line, *q;
                    int count = 0;
                    for (;;) {
                        long val = strtol(p, &q, 0);    // parse an integer
                        if (q == p) {
                            // end of string or not a number
                            break;
                        }
                        // value was read into val. You can use it for whatever purpose
                        count++;
                        p = q;
                    }
                    printf("%d\n", count);
                    break;
                } else {
                    lcount++;
                }
            }
            fclose(fp);
        }
        return 0;
    }
    

提交回复
热议问题