C - scan user inputs into an array to be sorted

本秂侑毒 提交于 2019-12-11 09:31:26

问题


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.


回答1:


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;
}



回答2:


You have it doing what you want, you just need a few tweaks. First, enter doesn't return -1, to keep it simple you need to enter ctrl+d to stop input. After your final input, just hit ctrl+d. Take a look:

#include <stdio.h>
#define MAX 100

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

    printf("Enter a list of integers [ctrl+d] to end\n");

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

    int z;
    for (z = 0; z < i; z++)
        printf("The array is %d\n", array[z]);

    return 0;
}

output:

Enter a list of integers [ctrl+d] to end
> 1
> 2
> 3
> 4
> 5
>
The array is 1
The array is 2
The array is 3
The array is 4
The array is 5


来源:https://stackoverflow.com/questions/23924896/c-scan-user-inputs-into-an-array-to-be-sorted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!