'How To Make The Placeholders In Scanf Variable?
What I mean by the question is this. For example, I add a scanf function that asks for the size of an array, which in this case is integer n. Now I want to form a loop that asks repeatedly for user input, but only until the size of the array.
printf("Enter the number of elements of the first array: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i<n; i++){
scanf("%d ", arr[i);
the problem is that I do not want to separate the user inputs with a newline variable. So instead of
10
20
30
40
I want it to be
10 20 30 40
How do I do this ?
Solution 1:[1]
Just expanding a little on I love python's comment
You're very close with the code you have already. Short answer: In the loop, remove the space after '%d' and add an addressof operator before arr[i].
But your code probably won't compile at the moment because you actually can't declare an array unless it's size is known at compile time (int arr[n]). You can, however, dynamically allocate it in memory using malloc() and free() (from stdlib.h) as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("Enter the number of elements of the first array: ");
scanf("%d", &n);
// Dynamically allocate the array (allows for variable size)
int* arr = (int*)malloc(n * sizeof(int));
for (int i = 0; i<n; i++) {
// Remove the space after '%d'
// Add addressof operator before arr[i]
scanf("%d", &arr[i]);
}
// Don't forget to free the allocated memory!
free(arr);
return 0;
}
The reason this works is because scanf returns as soon as it finds the requested input (an int, in this case). When it returns though, everything that it hasn't read gets left in the input buffer. When scanf executes again, it still has the rest of the user's input to read and it returns after reading the next int, and this keeps repeating until the loop condition is satisfied.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
