在下面的例子中,我希望能够接受0作为分子,但不能作为分母。我还希望排除非数字字符的输入。我觉得我缺少一些非常简单的东西,或者不太明白如何使用sscanf。
#include <stdio.h>
int main(int argc, char *argv[]) {
double numerator = 0.0;
double denominator = 0.0;
double result = 0.0;
if (argc == 3.0) {
sscanf(argv[1],"%lf", &numerator);
sscanf(argv[2],"%lf", &denominator);
result = numerator / denominator;
if (denominator == 0){
printf("invalid input - divide by zero not allowed\n");
}
else if (numerator == 0){
printf("invalid input\n");
}
else printf("%lf\n", result);
}
return 0;
}
答案 0 :(得分:0)
使用scanf系列函数来确保输入有效的惯用方法是尝试在数字后读取某些内容并控制只获得一个值:
if (argc == 3) {
char dummy[2];
if (sscanf(argv[1],"%lf%1s", &numerator, dummy) != 1) {
printf("%s is not a valid input\n", argv[1]);
return 1;
}
...
sscanf(argv[2],"%lf", &denominator);
输入后 %1s
只允许空白字符(主要是空格或换行符)