zhangdi zhangdi - 4 years ago 110
C Question

how to get the number of integer in a file with empty space in it

number.txt

1 2 3 4 5 6 7 8 9 10 11 12 13 14


For instance, I have the above text file. I would like to get the number of integer in the file (which is 14 in this case), and pass every integer into an array.

what I did is

int count = 0;
int i = 0;
while ( 1 )
{
int c = fgetc( fp );
if ( c == EOF || c == '\n' )
{
if ( c == EOF ) break;
}
else if(c ==' ')
{
++count;
--count;
}
else
{

++count;
arr[i] = c-48; // This line give me the wrong number so I subtract it by 48
++i;
}
}


In the case, the count will only get the correct value when there is no double digits number in the file(such as 10 11 12 13). Otherwise, it does not work.

I also tried to use fscanf to store every integer in an array, then get the length of the array. That does not work since I have to define the length of the array first and there is no way I can do that.

My question is how to deal with the double digits number in the file in order to get the right value. Is there a better to do that? Can someone help? Thanks in advance.

Answer Source

You can just read the integers with fscanf(), and every time a number is found, increment a counter.

Something as simple as this could work:

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

int main(void) {
    FILE *fp;
    int num;
    size_t count = 0;

    fp = fopen("somenumbers.txt", "r");
    if (!fp) {
        fprintf(stderr, "Error reading file\n");
        return 1;
    }

    while (fscanf(fp, "%d", &num) == 1) {
        count++;
    }

    printf("number of digits = %zu\n", count);

    fclose(fp);

    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download