- 2

How to scan double in array? C language

It's work on integer, but why doesnt work in float

11th Nov 2020, 7:32 AM
Briana
Briana - avatar
18 Antworten
+ 2
Briana do like that: scanf("%lf%*c ", arr[i]); %lf reads and save the double %*c reads snd discard a character (in your case a comma) " " reads and discard a space
11th Nov 2020, 10:01 AM
Davide
Davide - avatar
+ 2
Martin Taylor the spacing is not a problem - the spaces before the values read by format specifier are skipped, if you want to also allow spaces before the commas you can add a single space before the commas in a format specifier (space in format string means "skip all the whitespaces in current position"). In general you are right - once you need to read complicated input, it is better to use special tools. Strtok also has its problems (modifying the input string, having global state)
11th Nov 2020, 10:23 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
12th Nov 2020, 10:24 PM
Szaky
Szaky - avatar
+ 1
Something like this? float arr[4]; for(int i=0;i<4;i++){ scanf("%f",&arr[i]); printf("%f\n",arr[i]); } Briana this should do. float arr[4]; float sum = 0.0; for(int i=0;i<4;i++){ scanf("%f",&arr[i]); printf("%.2f\n",arr[i]); sum += arr[i]; } printf("sum = %.2f",sum);
11th Nov 2020, 7:52 AM
Avinesh
Avinesh - avatar
+ 1
What is your input and expected result?
11th Nov 2020, 8:09 AM
Avinesh
Avinesh - avatar
+ 1
Briana my previous code works fine, you just had to change the array length. https://code.sololearn.com/c0GLoeMD0dop/?ref=app
11th Nov 2020, 8:35 AM
Avinesh
Avinesh - avatar
+ 1
Just an addition. Since the title also mentions double, the format specifier to read double is %lf (since the pointers point to different sized objects scanf needs to know the size)
11th Nov 2020, 8:59 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
+ 1
Briana as an alternative, if you want to read comma separated values just put commas in the format string - like in the attached code (the spaces will be skipped by default). https://code.sololearn.com/czuCW75WA2g3/?ref=app
11th Nov 2020, 10:06 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
+ 1
Martin Taylor in your case you just need to prepend %*c with another space to skip spaces before. See the code i attached to my previous post. You can change spaces in input line and see it treats extra spaces (or no spaces) just fine https://code.sololearn.com/czuCW75WA2g3/?ref=app
11th Nov 2020, 11:36 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
0
Avinesh ya.. But i want %.2f and sum all array. It doesnt work
11th Nov 2020, 7:55 AM
Briana
Briana - avatar
0
Avinesh it doesnt work
11th Nov 2020, 8:06 AM
Briana
Briana - avatar
0
Avinesh my input is 12 number of float array like 10.00, 10.10, 10.20, and so on. The expected result is the sum of all number
11th Nov 2020, 8:16 AM
Briana
Briana - avatar
0
Avinesh thankyou. But how if the input contain comma and space?
11th Nov 2020, 8:47 AM
Briana
Briana - avatar