Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get several value in once enter ?(Number of uncertainty)

Tags:

c

scanf

How can I get several values input from the keyboard (an integer type and many number of uncertainty) ?

I need to write a program which allow users to enter any number , Each number is delimited by the Space and when the user presses Enter, The number was placed in each of the variables Array.

For example,

input number: 1 2 8 9 (Enter) if input the fourth (numbers), it will build up four variables to get that value.

number [0] = 1, number [1] = 2, number [2] = 8, number [3] = 9.

input number: 3 4 7 (Enter) if input the third (numbers), it will have to build up three variables to get that value.

number [0] = 3, number [1] = 4, number [2] = 7.

I tried to use the scan f function,but it's not work ,

If have any good advice ,please tell me

#include <stdio.h>
#include <windows.h>

int n, number[10];

main()
{
    printf("Enter Number of integer : ");
    scanf("%d", &n);
    if (n == 1) {
        printf("Enter integer : ");
        scanf("%d", &number[0]);
    } else if (n == 2) {
        printf("Enter integer : ");
        scanf("%d %d", &number[0], &number[1]);
    } else if (n == 3) {
        printf("Enter integer : ");
        scanf("%d %d %d", &number[0], &number[1], &number[2]);
    }
    system("pause");
}
like image 582
Kaiketsu Zorori Avatar asked Apr 27 '15 15:04

Kaiketsu Zorori


1 Answers

Have you considered doing this using a combination of scanf(), fgets() and strtok()?

For example, you can use scanf() to simple query the number of inputs expected. Then use a loop around `strtok() to tokenize user's input:

int main()
{
    char line[1024];
    char *token = {0};
    char delim[]={" \r\n\t"};
    long telPos = 0;
    int count, i;
    int *array = {0};

    printf("Enter Number of integers, <return> then line of integers : \n");
    scanf("%d",&count);

    getchar();//eat the newline (from <return>)

    while (fgets(line, 1024, stdin) != NULL)
    {
        array = malloc(sizeof(int)*count);
        token = strtok(line, delim);
        i = -1;
        while(token)
        {
            if((count - 1) > i++)
            {
                array[i] = atoi(token);
                token = strtok(NULL, delim);
            }
            else
            {
                for(i=0;i<count;i++) printf("value %d: %d\n", i, array[i]);
            }
        }
        //do something here with array, then free it.
        free(array);
    }

    return 0;

}
like image 162
ryyker Avatar answered Nov 15 '22 05:11

ryyker