Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading