C, reading multiple numbers from a single scanf

arrayscconsolescanf

I have an assignment that requires me to take a single scanf and perform some math operations to several integers. The first number in the input sets the number of integers to follow ie: 3 45 67 18 should be interpreted as N var1 var2 var3 and 4 100 23 76 92 should be interpreted as N var1 var2 var3 var4. I couldnt make the program as instructed on my first iteration but it does work as its supposed to. I accomplish storing var1 var2… varN by simply putting scanf in a loop that runs N times and storing the remaining numbers in an array n[1000]. Like I said the program works… sorta, but it doesnt work the way the assignment instructed. The sample run provided by the assignment should be:

Please enter n followed by n numbers: 3 6 12 17

Test case #1: 6 is NOT abundant.
Test case #2: 12 is abundant.
Test case #3: 17 is NOT abundant.

My program output is:

Please enter n followed by n numbers: 3
6
12
17
Test case #1: 6 is NOT abundant.
Test case #2: 12 is abundant.
Test case #3: 17 is NOT abundant.

Here is the link to my program.
I have read through many of the similar questions, but most seem to trivialize the use of scanf as opposed to other methods of capturing input from the console. This post is extremely close to the answer that I am looking for except I need a dynamically set number of variables. I have a feeling I need to use the malloc function but im just not quite sure how to use it for this and still accomplish a single line of scanf input.

Thanks

Best Answer

Okay I tested it and you can indeed do this with scanf.

#include<stdio.h>

int main(){
    int total = 0;
    int args;
    char newline;
    do{
        int temp; 
        args = scanf( "%d%c", &temp, &newline );
        if( args > 0 )
            total += temp;
        puts( "Internal loop print test");
    } while( newline != '\n' );
    printf( "\n\n%d", total );
    return 0;
}

Console log:

1 2 3 9
Internal loop print test
Internal loop print test
Internal loop print test
Internal loop print test


15

Edit: I never use the scanf family due to several known vulnerability issues, but it didn't even occur to me to try and use scanf. I assumed it would read to the newline, but it works just fine with scanf. Aniket's comment made me want to try it.