TransWikia.com

Taking input of unknown size of array

Stack Overflow Asked by Subhradwip Ghosh on December 13, 2021

#include <stdio.h>
int main() 
{
    int a[50],i,n=0;
    while(scanf("%d",&a[n++])!=EOF);
    n--;
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
    return 0;
}

Let,

Input: 5 6 7 8 9

Output: 5 6 7 8 9

My question is why the above code works in Online C Compiler and gives proper EOF(-1)

But while running the code in offline C IDE like Codeblocks, it results in an infinite loop of input as it is not giving any EOF, and what to do to get a similar result in an offline compiler?

One Answer

The scanf() function returns the number of input values it scanned.

In case of input error or failure it returns EOF. As suggested in the comments you can compare the scanf() return value to 1 in order to see if it had a valid input. So if your input is anything other than an int it will end the loop.

Also making sure n is still within the array bounds before calling the scanf() is a good idea.

So you can write the code like this

#include <stdio.h>

int main ()
{
    int a[50], n = 0;

    while((n < 50) && (scanf("%d", &a[n++]) == 1));

    n--;

    for (int i = 0; i < n; i++)
    {
        printf("%d", a[i]);
    }
    
    return 0;
}

Answered by Abcd Efg on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP