Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

c - How to only accept a certain precision (so many decimals places) in scanf?

In scanf() function I want to take only upto decimal values.Can we achieve it? For example for displaying upto two decimal places we use printf("%.2f",A) How can we do it for scanf() function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

scanf() does not have a simple method to meet OP's goal.
Recommend using fgets() for input and then parse the string.

char buf[20];
fgets(buf, sizeof buf, stdin);  // Could add check for NULL here

To limit to 2 decimal places, code could read the number in parts: integer portion and fraction, then form the result:

long long ipart;
unsigned d[2];
int n;
if (sscanf(buf, "%lld.%1u%1u %n", &ipart, &d[0], &d[1], &n) != 3 || buf[n]) {
  Handle_InvalidInput();
}
double value = (d[0]*10 + d[1])/100.0;
value = ipart + ipart < 0 ? -value : value;

Even though this fulfills OP's quest, I do not think it solves OP's larger goal. So rather than limit input, read the input and then qualify it:

double value;
if (sscanf(buf, "%lf %n", &value, &n) != 1 || buf[n]) {
  Handle_InvalidInput();
}
double rounded_value = round(value * 100.0)/100.0;
if (rounded_value != value) {
  Handle_OverlyPreciseNumber(value, rounded_value);
}

Other more pedantic methods would inspect the string buf for ddd...ddd.dd syntax, etc. But the issue is clear: read the data and then qualify the data read. Do not attempt to restrict the input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...