- 2
How to scan double in array? C language
It's work on integer, but why doesnt work in float
14 Answers
+ 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
+ 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)
+ 2
Briana
Try this example:
https://code.sololearn.com/cGSXq436ena4/?ref=app
+ 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);
+ 1
What is your input and expected result?
+ 1
Briana my previous code works fine, you just had to change the array length.
https://code.sololearn.com/c0GLoeMD0dop/?ref=app
+ 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)
+ 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
+ 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
0
Avinesh ya.. But i want %.2f and sum all array. It doesnt work
0
Avinesh it doesnt work
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
0
Avinesh thankyou. But how if the input contain comma and space?