c - One digit after the decimal point in input -


this question has answer here:

how can take floating point number 1 digit after decimal point (0.1) using scanf in c language ? example user may type 3.25405... in variable 3.2 saved . how can ? different rounding floating point number .

read using fgets() , post-process buffer. @devsolar

char buf[100]; if (fgets(buf, sizeof buf, stdin) == null) handle_eof(); char *p = strchr(buf,'.'); if (p && isdigit(p[1])) p[2] = 0; char *endptr; double y = strtod(buf, &endptr); ... 

even better alert user of ignored additional input.

if (p && isdigit(p[1])) {   if (p[2] && p[2] != '\n') puts("extra input ignored.");   p[2] = 0; } char *endptr; double y = strtod(buf, &endptr); 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -