程序要求用户输入一个初始值,允许范围在 0 到 1000 之间,包括小数位
如何创建错误控制来拒绝字符、空格或额外的小数点,例如 1.2.3? n 循环自身提示用户输入新内容
<小时/>printf("Please enter initial velocity(in m/s) of ball when thrown vertically upwards: \n");
scanf("%lf%c",&v0,&rubbish);
printf("%f\n",v0);
printf("%c\n",rubbish);
/*error control for incorrect range of value entered*/
while (v0<0 || v0> 1000|| rubbish !='\n')
{
/*Ask user for correct value of velocity*/
v0='\n', rubbish="\n";
printf("\nIncorrect value keyed\n");
printf("Please enter again the initial velocity(in m/s) of ball when thrown vertically upwards: \n");
scanf("%lf",&v0);
scanf("%c",&rubbish);
printf("%f\n",v0);
printf("%c\n",rubbish);
}
最佳答案
how to implement strtod() when i have to get keyed values?
我将其理解为:您想从用户那里获得双倍(我将您的评论中的“键入”理解为“在键盘上键入”)。附加约束是输入行不应包含任何其他字符或额外的小数。
您可以分两步完成:
- 读取行
- 解析 double
从标准输入读取行
#include <stdio.h> // fgets
#include <string.h> // strlen
// ...
char buf[BUFSIZ];
char *s = NULL;
if ((s = fgets(buf, BUFSIZ, stdin)) == NULL || strlen(s) == (BUFSIZ-1)) {
// can't read from stream or line is too long
return -1; // return <0 from your function to indicate error to the caller
}
此时s
包含用户输入。
使用strtod()
解析 double
strtod()
可以检测许多错误情况:上溢、下溢、空字符串或前导非空白字符无法解释为 float 。接口(interface)可能会令人困惑(并且 c89 和 c99 之间的一些极端情况发生了变化)。您可以查看并选择您想要检测并忽略其他条件的条件。
下面是一个示例,要求字符串仅包含数字和可选的前导、尾随空格,仅包含其他内容:
#include <ctype.h> // isspace
#include <errno.h>
#include <math.h> // HUGE_VAL
#include <stdlib.h> // strtod
// ...
int ret = 0;
char *endptr = NULL;
double d = 0.0;
int save = errno; // save original value
errno = 0; // clear
if (out && // double *out (function parameter)
!(((d = strtod(s, &endptr)) == 0.0 || d == HUGE_VAL || d == -HUGE_VAL) &&
(str == endptr || errno == EINVAL || errno == ERANGE))) {
// `d` contains a number
// check what left in the string
while(isspace(*endptr))
++endptr; // skip whitespace
if (*endptr == '\0')
*out = d; // success
else
ret = -1; // error: non-whitespace encountered after the number
}
else
ret = -1; // error: can't read a number
errno = save; // restore
return ret;
关于c - 如何对拒绝字符、空格和多余小数点进行错误控制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7856769/