arrays - C, reading multiple numbers from a single scanf -
i have assignment requires me take single scanf , perform math operations several integers. first number in input sets number of integers follow ie: 3 45 67 18 should interpreted n var1 var2 var3 , 4 100 23 76 92 should interpreted n var1 var2 var3 var4. couldnt create programme instructed on first iteration work supposed to. accomplish storing var1 var2... varn putting scanf in loop runs n times , storing remaining numbers in array n[1000]. said programme works... sorta, doesnt work way assignment instructed. sample run provided assignment should be:
please come in n followed n numbers: 3 6 12 17 test case #1: 6 not abundant. test case #2: 12 abundant. test case #3: 17 not abundant. my programme output is:
please come in n followed n numbers: 3 6 12 17 test case #1: 6 not abundant. test case #2: 12 abundant. test case #3: 17 not abundant. here link program. have read through many of similar questions, seem trivialize utilize of scanf opposed other methods of capturing input console. this post extremely close reply looking except need dynamically set number of variables. have feeling need utilize malloc function im not quite sure how utilize , still accomplish single line of scanf input.
thanks
the next code worked me:
#include <stdio.h> #include <stdlib.h> int main(void) { int n[1000],i,j,sum,size; printf("please come in n followed n numbers: "); scanf("%d",&n[0]); (i=1;i<=n[0];i++) scanf("%d",&n[i]); /* debug: automatically generate numbers 1 n[0] */ //n[i]=i (i=1;i<=n[0];i++) { /* debug: see numbers beingness used in sum - part 1*/ //printf("\nfactors < %d of %d: ",n[i]/2,n[i]); sum=0; (j=1;j<=n[i]/2;j++) { if (n[i]%j==0) { /* debug: see numbers beingness used in sum - part 2*/ //printf("%d ",j); sum+=j; } } printf("test case #%d: %d is%sabundant.\n",i,n[i],(sum>n[i])?" ":" not "); /* debug: see numbers beingness used in sum - part 3*/ //printf("(%d)\n",sum); } system("pause"); homecoming 0; } aslai reply had me perplexed because couldnt see how code accomplish different did. while debugging see scanf returned noticed scanf returns after every space instead of on "enter" or "\n" thought. simplified first loop , works. right in saying input 1 scanf satisfy variable assignments subsequent scanf's long there sufficient subsequent calls scanf? in other words if entered 3 25 17 during single scanf can assign each of numbers variables subsequent scanf calls without having pressing enter?
scanf("%d",&var1); //(where var1=3) scanf("%d",&var2); //(where var2=25) scanf("%d",&var3); //(where var3=17) c arrays console scanf
No comments:
Post a Comment