Code Blocks error when using while(scanf) in C

Viewed 286

I have attached a piece of code below which works perfectly fine in an online compiler but fails to work in Code Blocks compiler when using C. I have attached screenshots as well.

#include <stdio.h>

int main() {
    int i = 0;
    int array[100];
    while(scanf("%d",&array[i])>0)
    {
        i++;
    }
    for(int j=0;j<i;j++)
    {
        printf("%d ",array[j]);
    }
    return 0;
}

Using Online compiler(GeeksForGeeks)

Using CODEBLOCKS compiler

1 Answers

There is no error, your while loop will go on until an invalid input is entered, you have no limit for the number of inputs so it will continue taking values, which may later become a problem since your container only has space for 100 ints.

It stops on some online compilers because of the way they use stdin inputs, it's basically a one time readout.

Examples:

It stops here, has one time stdin readout.

It doesn't stop here, has a console like input/output.

So if you want to stop at a given number of inputs you can do something like:

//...
while (i < 5 && scanf(" %d", &array[i]) > 0)
{
    i++;
}
//...

This will read 5 ints, exit the loop and continue to the next statement.

If you don't really know the number of inputs, you can do something like:

//...
while (i < 100 && scanf("%d", &array[i]) > 0) { // still need to limit the input to the
                                                // size of the container, in this case 100
    i++;
    if (getchar() == '\n') { // if the character is a newline break te cycle  
                             // note that there cannot be spaces after the last number
        break;
    }
}
//...

The previous version lacks some error checks so for a more comprehensive approach you can do somenthing like this:

#include <stdio.h>
#include <string.h> // strcspn
#include <stdlib.h> // strtol
#include <errno.h>  // errno
#include <limits.h> // INT_MAX

int main() {

    char buf[1200]; // to hold the max number of ints
    int array[100];
    char *ptr; // to iterate through the string
    char *endptr; // for strtol, points to the next char after parsed value
    long temp; //to hold temporarily the parsed value
    int i = 0;

    if (!fgets(buf, sizeof(buf), stdin)) { //check input errors

        fprintf(stderr, "Input error");
    }

    ptr = buf; // assing pointer to the beginning of the char array

    while (i < 100 && (temp = strtol(ptr, &endptr, 10)) && temp <= INT_MAX 
    && errno != ERANGE && (*endptr == ' ' || *endptr == '\n')) {

        array[i++] = temp; //if value passes checks add to array
        ptr += strcspn(ptr, " ") + 1; // jump to next number
    }

    for (int j = 0; j < i; j++) { //print the array

        printf("%d ", array[j]);
    }
    return EXIT_SUCCESS;
}
Related