sgerbhctim sgerbhctim - 3 years ago 183
C Question

How to read space-separated values in C?

I have a .txt file that I am using to learn some basic C.

Here is the txt file:

8
12 48 15 65 16 82 9 72


Here is my C program:

#include <stdio.h>
#include <stdlib.h>



int main(int argc, char** argv){

char num = 0;
//int[] arr = 0;


if (argc != 2){
return 0;
}

FILE *inputFile = fopen(argv[1], "r");

if (inputFile == NULL){
printf("Error1\n");
return 0;
}

while(!feof(inputFile)){
num = fgetc(inputFile);
printf("%c\n",num);
}

if(!feof(inputFile)){
printf("error");
return 0;
}

}


My goal is the get an array of the second line, based on the amount of values in the first line.... essentially, we want an array with 8 values, that stores {12, 48, ....}

Answer Source

You are using a wrong function to read integers: in spite of returning an int, function fgetc is reading individual characters (why getchar returns an int?).

In order to read space-separated integers, use fscanf instead, and check the return value to decide that you have reached the end of file:

int n;
while (fscanf(inputFile, " %d", &n) == 1) {
    printf("%d\n", n);
}

Note that the loop above avoids using feof to detect the end of file condition (why using feof is wrong?)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download