Search code examples
carraysfgets

fgets, sscanf, and writing to arrays


beginner question here, I haven't been able to find examples that relate. I'm working on a C program that will take integer input from stdin using fgets and sscanf, and then write it to an array. However, I'm not sure how to make fgets write to the array.

#define MAXINT 512
char input[MAXINT]

int main(void) {
    int i;
    int j;
    int count=0;
    int retval;
        
    while (1==1) {
        fgets(input, MAXINT[count], stdin);
        retval = sscanf(input, "%d", &i);
        
        if (retval == 1) {
            count = count++;
        } else if (retval != 1) {
            break;
        }
    }
}

Would I simply put fgets in a for loop? or is it more complicated than that?


Solution

  • One can put fgets() & ssprintf() in one long condition:

    #define MAXINT 512 /* suggest alternate name like Array_Size */
    int input[MAXINT];
    char buf[100];
    int count = 0;
    
    while ((NULL != fgets(buf, sizeof buf, stdin)) && (1 == sscanf(buf,"%d",&input[count]))) {
      if (++count >= MAXINT) break;
    }
    

    ... or something a bit more user friendly:

    // While stdin not closed and input is more than an "Enter" ...
    while ((NULL != fgets(buf, sizeof buf, stdin)) && (buf[0] != '\n')) {
      if (1 != sscanf(buf,"%d",&input[count])) {
        puts("Input was not an integer, try again.\n");
        continue;
      }
      if (++count >= MAXINT) break;
    }