Home > database >  What would be the best way to get multiple inputs in c?
What would be the best way to get multiple inputs in c?

Time:12-09

I got an assignment to get a list of inputs and use it (the use itself does not matter). The input is will end only with EOF. I need to get a list of numbers and fill an array with the size of n. Every number is separated with white chars. I input also needs to be checked because it is not promised it is valid.

I have a few ways of doing that and I would like to know what would be considered best and why. (maybe I did not even consider the best solution so any suggestions are very welcome)

I use ubuntu.

Solution 1: Using getchar() until EOF while checking for white chars to separate the numbers.

Solution 2: Using scanf() doing something like that:

char str[256];

while (scanf("%s", str) != EOF)
{
    // Check the input and add to the array.
}

I think that this is the best solution but the problem is that I need to press control d twice to end input and it is not valid.

Solution 3: Using fgets() and read to a buffer and work with the buffer. I think it complicates the problem because an integer can be split across 2 buffers.

Thanks for all helpers.

CodePudding user response:

In general, validating input with scanf is difficult. But for simple input like this you can do:

while( scanf("%d", &n) == 1 ){
    /* add n to the array. */
}
if( ferror(stdin) ){
    fprintf(stderr, "Read error\n");
} else if( ! feof(stdin) ){
    fprintf(stderr, "Invalid input\n");
}

The while loop will terminate upon EOF or an invalid entry. feof() will decide whether or not the input stream was closed.

  • Related