In c, I can use scanf to read say 3 integers separated by spaces from standard input like this:
#include <stdio.h>
int main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
}
What if I don't know how many integers are in the row before hand? Say the user provides the number of integers:
#include <stdio.h>
int main() {
int howManyIntegersToRead;
scanf("%d", &howManyIntegersToRead);
// Read in the integers with scanf( ... );
}
I'll need to malloc an array of size sizeof(int) * howManyIntegersToRead bytes. How do I actually read the standard input data into the allocated memory? I can't construct a formatted string with howManyIntegersToRead %ds. Well, I could, but there's got to be a better way.
You may try like this using for loop:
int i, size;
int *p;
scanf("%d", &size);
p = malloc(size * sizeof(int));
for(i=0; i < size; i++)
scanf("%d", &p[i]);
#include <stdio.h>
int main() {
int howManyIntegersToRead;
scanf("%d", &howManyIntegersToRead);
// Read in the integers with scanf( ... );
// allocate memory
int a[howManyIntegersToRead];
for(int i=0;i<howManyIntegersToRead;i++)
scanf("%d",&a[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With