Search code examples
csortingintegeruser-input

C - scan user inputs into an array to be sorted


Forgive me, I'm a C programming rookie. What I need to do is take values from standard input and store them in an array which is to be sorted later on down the line.

The method of entry for the user is one number on one line at a time (i.e. enter a number, press enter, enter number, press enter, etc..). When the user is done entering numbers, they press ENTER without providing a number.

My code for accepting the values and storing them is as follows. You'll probably see the issue immediately, but I'm not seeing it.

#include <stdio.h>
#define MAX 100

int main()
{
    int n, i, array[MAX];

    printf("Enter a list of integers\n");

    for(i = 0; i <= MAX; ++i){
        printf("> ");
        if (scanf("%d", &n) == -1)
            break;
        else
            scanf("%d", &n);
            array[i] = n;
    }

    printf("The array is %d", *array);
    return 0;
}

The picture below is how the program should run. I have the sort code already, and it seems to work quite well. Your help is greatly appreciated.

enter image description here


Solution

  • Here is the updated previous answer to exit on enter.

    #include <stdio.h>
    #define MAX 100
    
    int main()
    {
        int n, i, array[MAX];
        char num[MAX];
        int res;
    
        printf("Enter a list of integers [ctrl+d] to end\n");
    
        for(i = 0; i <= MAX; ++i){
            printf("> ");
            fgets(num, sizeof(num), stdin);
            res = sscanf(num, "%d", &n);
            if(res != 1)
                break;
            n = atoi(num);
            array[i] = n;
        }
        puts ("");
    
        int z;
        for (z = 0; z < i; z++)
            printf("The array is %d\n", array[z]);
    
        return 0;
    }