Sandeep Kaushik
Sandeep Kaushik

Reputation: 31

Reading integers from a file separated with spaces

I am having a file which is holding integers like this:

11_12_34_1987_111_       

where _ represents spaces and i want to store them in integer array having max size suppose 100. I have tried this

    i=0;
    while((c=fgetc(f))!=EOF)
    {

        fscanf( f, "%d", &array[i] );
        i++;
    }

but printing this array gives me infinite values on my Screen.

Upvotes: 0

Views: 5865

Answers (1)

ajay
ajay

Reputation: 9680

fgetc reads the next character from the stream f and returns it as an unsigned char cast to an int. So you are storing the (ascii) codes of the characters read from the stream.

You should read them as integers using fscanf or a combination of fgets and sscanf to read integers from the stream. You can check the return value of fscanf for 1 and keep reading from the file. Here's what I suggest.

FILE *fp = fopen("input.txt", "r");
int array[100];
int i = 0, retval;

if(fp == NULL) {
    printf("error in opening file\n");
    // handle it
}

// note the null statement in the body of the loop
while(i < 100 && (retval = fscanf(fp, "%d", &array[i++])) == 1) ; 

if(i == 100) {
    // array full
}

if(retval == 0) {
    // read value not an integer. matching failure
}

if(retval == EOF) {
    // end of file reached or a read error occurred
    if(ferror(fp)) {
        // read error occurred in the stream fp
        // clear it
        clearerr(fp);
    }
}

// after being done with fp
fclose(fp);

Upvotes: 2

Related Questions