Search code examples
carraysfileinputeol

How to read number to string till end of the line in C


I have an input file like this

10 25 4 3 86 1 23 20 14 1 3 7 3 16 7
2

The 1st line: An array of number.

The 2nd line: An integer k.

I tried fgets() to read them but it's not working. Here is my code:

int main(){
    FILE *input = fopen("Input7.txt","r");
    int a[2000],k;
    fgets(a,2000,input);
    fscanf(input,"%d",&k);
    fclose(input);
    int i,n;
    n = 15; //My example array have 15 numbers
    for (i=1;i<=n;++i){
        printf("%d  ",a[i]);
    }
    return 0;
}

I printed out the array a after i read it but here is what i got Photo links

How can i fix this problem ? Btw, i want to count how much number i've read into the array. Thanks for your help.


Solution

  • You have to change the type of your a array to char, because the fgets waits for char* as first parameter.

    The next important thing is that fgets read the characters into the specified char array not the numbers directly, you have to tokenize the charater sequence you read and convert each token to integer. You can tokenize your a array with the strtok function.

    #include <stdio.h> // for fgets, printf, etc.
    #include <string.h> // for strtok
    
    #define BUFFER_SIZE 200
    
    int main() {
        FILE* input = fopen("Input7.txt", "r");
        char a[BUFFER_SIZE] = { 0 };
        char* a_ptr;
    
        int k, i = 0, j;
        int n[BUFFER_SIZE] = { 0 };
    
        fgets(a, BUFFER_SIZE, input); // reading the first line from file
        fscanf(input, "%d", &k);
    
        a_ptr = strtok(a, " "); // tokenizing and reading the first token
        while(a_ptr != NULL) {
            n[i++] = atoi(a_ptr); // converting next token to 'int'
            a_ptr = strtok (NULL, " "); // reading next token
        }
    
        for(j = 0; j < i; ++j) // the 'i' can tell you how much numbers you have
            printf(j ? ", %d" : "%d", n[j]);
        printf("\n");
    
        fclose(input);
        return 0;
    }