I came across this code
Input:
3
0.1227...
0.517611738...
0.7341231223444344389923899277...
int N;
char x[110];
int main() {
scanf("%d\n", &N);
while (N--) {
scanf("0.%[0-9]...\n", &x);
printf("the digits are 0.%s\n", x);
And I cannot understand few things:
1.Why aren't we using a double array(since the input value is double)?
2.What purpose do those three dots ... in scanf after [0-9] are serving? and
3.Why are we not using any format specifier (d in this case) after [0-9] in scanf?
Why aren't we using a double array(since the input value is double)?
The inputs could be captured as double as well as characters. double does have a limit of significant digits. For whatever reason, your code is storing the input as characters.
What purpose do those three dots ... in scanf after [0-9] are serving?
The three dots aren't serving any purpose except if they are part of the input then up to three dots are removed before the next scanf. An input of 0,123 will be successfully scanned as will 0.123.... If the input was 0.123abc the abc will be left in the input stream and cause problems in the current code.
Why are we not using any format specifier (d in this case) after [0-9] in scanf?
%[] is a format specifier. Sometimes called a scanset. It stores characters. It can be inclusive or exclusive.
%[0-9] is inclusive. It will accept digits. It will stop on the first character that is not a digit.
A d following the specifier would behave the same as the dots. With 0.%109%[0-9]d, an input of 0.123down would scan 0.123d leaving own in the input stream to cause problems later on in the current code.
It is a good practice to provide the array limit to prevent writing too many characters to the array. for [110] use %109[0-9]. That allows one character for the terminating zero.
EDIT: code example
#include <stdio.h>
int N;
char x[110];
int main ( void) {
scanf("%d\n", &N);
while (N--) {
scanf(" 0.%109[0-9]...", x);
printf("the digits are 0.%s\n", x);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With