0

I am receiving a file as an argument in a C program

Each line has different numbers of integer like this :

1 2 4 5 6
7 8 8 9 10 -1 2 3
12 3 4 -2 2 -3 9 2 4

I want to get the first 2 arguments of each line into some int and all the rest into an array something like this for line #2 :

int a;
int b;
int c[10];

int a = 7;
int b = 8;
int c = [8,9,10,-1,1,2,3]

I am able to obtains the first 2 but I can't make it happens for the array.

Any help would be appreciated

This is what I have right now:

//get line per line until \n
while (fscanf(fp, "%d %d", a, b) != EOF)
    while (fscanf(fp,"%d [^\n]", c[n]) != EOF)
        n++;

// print each line
for ( int k = 0 ; k < 10; k ++)
    printf("%d %d %d \n", a, b, c[k]);
gsamaras
  • 71,951
  • 46
  • 188
  • 305
dopeinc
  • 59
  • 1
  • 6

2 Answers2

0

Separating out lines using just fscanf can be tricky. You're better off reading a single line with fgets then using sscanf to read the numbers from there.

Also, fscanf and sscanf return the number of items matched. You shouldn't be checking for EOF.

char line[300];
while (fgets(line, sizeof(line), fp)) {
    int rval = sscanf(line, "%d %d", &a, &b);
    if (rval == 2) {
        int count = 0;
        do {
            rval = sscanf(line, "%d", &c[count++]);
        } while (rval == 1);
    } 
}
dbush
  • 205,898
  • 23
  • 218
  • 273
0

Read C read file line by line and How to extract numbers from string in c?, and then you would end up with something like this:

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

int main(void) {
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("input.txt", "r");
    if (fp == NULL)
        return -1;

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        //printf("%s", line);
        char* p = line;
    int a, b, c[10], counter = -2;
    while (*p) { // While there are more characters to process...
            if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
                // Found a number
                long val = strtol(p, &p, 10); // Read number
                //printf("%ld\n", val); // and print it.
            if(counter == -2)
                a = val;
            else if(counter == -1)
                b = val;
            else if(counter < 10)
                c[counter] = val;
            counter++;
            } else {
                // Otherwise, move on to the next character.
                p++;
            }
    }
    printf("a = %d, b = %d\n", a, b);
    for(int i = 0; i < counter; ++i)
        printf("%d ", c[i]);
    printf("\n");
    }

    fclose(fp);
    if (line)
        free(line);
    return 0;
}

Output:

Retrieved line of length 10:
a = 1, b = 2
4 5 6 
Retrieved line of length 18:
a = 7, b = 8
8 9 10 -1 2 3 
Retrieved line of length 21:
a = 12, b = 3
4 -2 2 -3 9 2 4 
gsamaras
  • 71,951
  • 46
  • 188
  • 305