Hmerac
Hmerac

Reputation: 187

Can't get the input that I want to

I just started C programming and I'm a newbie. I did some research but unfortunately couldn't find anything about my problem. Can't use array BTW that's why i don't use it.

So, I'm making a function to print stars as many as given number. But function is printing the last input number.

#include <stdio.h>

int main(){

    void pstr(int *m){
        int j;
        for(j = 0; j < *m; j++)
            printf("*");
            printf("\n");
    }

    int i;
    int number = 9;
    int n1, n2, n3, n4, n5, n6, n7, n8, n9;

    printf("Enter 9 numbers (all less than 50):\n|1-2-3-4-5-6-7-8-9|\n");   
    printf("|-----------------|\n ");        
    for(i=0; i < number; i++)                                           
        scanf("%d", &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9);

    pstr(&n1);

    system("PAUSE");
}

I'm trying to print the first input number, but It's writing the last one(n9). Sorry about my English, Thank you.

Upvotes: 0

Views: 97

Answers (3)

Murtaza Zaidi
Murtaza Zaidi

Reputation: 597

 scanf("%d %d %d %d %d %d %d %d %d ", &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9);

Though better way would be to use an array and a loop. Since you are a novice I don't think you know about it yet. Use this for the moment.

Upvotes: 3

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

Declare numbers as:

int n[9];

instead of

int n1, n2, n3, n4, n5, n6, n7, n8, n9;

Then use the loop as:

for(i=0; i < number; i++)                                           
        scanf("%d", &n[i]);

Also, before using scanf, fflush the output buffer,

fflush(stdout);

Upvotes: 0

unwind
unwind

Reputation: 399743

Your scanf() format string is wrong.

scanf("%d", &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9);

You must have one % for each conversion, so 9 in your case. That would mean that the for is pointless.

Also, you must check that scanf() returns the expected number of successful conversions, otherwise you can't depend on the variables having proper values.

Upvotes: 3

Related Questions