How to read in a text file of tab-separated integers in C?

后端 未结 3 1715
小蘑菇
小蘑菇 2021-01-21 03:12

I have a file of simply tab-separated integers (a .txt file) and I wish to read them in with just C, line by line. So, say each line has 5 integers. How can I accomplish this?

3条回答
  •  广开言路
    2021-01-21 03:55

    #include 
    int main(){
        FILE *fp;
        int scanned = 0;
        int some_ints[5];
        fp = fopen("test.txt", "r");
        while ((scanned = fscanf(fp, "%d %d %d %d %d", some_ints, some_ints+1, some_ints+2, some_ints+3, some_ints+4)) !=  EOF) {
            if(scanned ==5){
                printf("%d %d %d %d %d\n", some_ints[0], some_ints[1], some_ints[2], some_ints[3], some_ints[4]);
            }
            else {
                printf("Whoops! Input format is incorrect!\n");
                break;
            }
        } 
    }
    

提交回复
热议问题