Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I scanf a row of n integers?

Tags:

c

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.

like image 330
dangerChihuahua007 Avatar asked Nov 29 '25 16:11

dangerChihuahua007


2 Answers

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]);
like image 101
Rahul Tripathi Avatar answered Dec 01 '25 15:12

Rahul Tripathi


#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]);
}
like image 26
Aseem Goyal Avatar answered Dec 01 '25 15:12

Aseem Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!