How do I get multiple numbers from one string in C?

If I want to get 3 numbers, I can write code like this:

scanf("%d %d %d", &a, &b, &c);

      

but , how can I dynamically get the number of inputs from one line?

For example, if the user enters N (number), then I should get N integers of inputs from one line as above.

Entry and exit should be:

how many do you want to enter: 5
1 2 3 4 5
sum: 15

      

+3


source to share


3 answers


Since it scanf

returns the number of filled variables, you can loop until scanf

there is more value to read or match the counter:



int count = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);
int val = 0;
int sum = 0;
int i = 0;
while(scanf("%d ", &val) == 1 && i++ < count)
  sum += val;

      

+5


source


Since you don't know the size of the inputs before, it's better to create a dynamic array based on the size of the input provided by the user. Enter the size of the array and create an array of that size. Then you can easily walk through the array and do whatever you want with it.



int count = 0, sum = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);

int *num = malloc(sizeof(int)*count);

for(int i = 0; i < count; i++) {
    scanf("%d ", &num[i]);
    //sum += num[i];
}

      

+1


source


As someone already said, you can just read it as a string, separating the values ​​when you see a space. In c, if you have a number such as 5 that is a character, you can turn it into a number by doing the following:

int foo = '5' - '0' //foo is now 5

      

and for more than one digit number, you can loop through the string and find your position and multiply it by 10 and then add them up

EDIT: also forgot to mention, but you can use atoi, which takes a char * and converts it to a number

-3


source







All Articles