我想检查用户的输入,如果他的输入是浮点数还是整数,那么接受它,然后对它进行一些数学运算,否则如果他的输入是字符、符号、大数或其他任何东西,那么数字会要求他输入另一个输入。提示我使用的数据类型为"p.burst_time“。但是每次输入任何输入时,程序都会认为它是错误的输入,因为检查器变成=1,甚至输入都是正确的&我不知道为什么。提前谢谢。
for(;;){
int i,checker,point=0;
char c[25];
c[strlen(c)-1] = '\0';
printf("\nEnter The Process's Burst Time > 0 : ");
fgets(c, 21, stdin); //Max input is 20.
fflush(stdin);
for(i=0;i<strlen(c);i++) //strlen(c) is the size. Max is 20.
{
if(c[i]=='.')
point++;
else if(!isdigit(c[i])){
checker=1; //Checker is 1 when input isn't a digit.
break;
}
}
printf("checker = %d\npoint = %d\n",checker,point);
if(checker==1||point>1){
printf("\a\aPlease enter a positive number only greater than zero.\n"); //Input has space, symbols, letters. Anything but digits.
continue;
}
else
{
p.burst_time = atof(c); //Converting to float only if input is nothing but digits.
if(p.burst_time<=0)
continue;
else
break;
}
}发布于 2015-05-10 22:50:58
一些问题:
\n:您应该忽略它和初始和终端空格(' '、\r、\t、\f,至少第2段)。c[strlen(c)-1] = '\0';没有任何意义:您尝试使用null来终止数组,但是strlen只给出了第一个空值的位置,它在统一数组上的行为是没有定义的(感谢WhozCraig注意到它):您可以执行c[0] = '\0';,或者c[sizeof(c) - 1] = '\0';,但是在这里,它仍然是无用的。我没有尝试运行它,所以我不知道是否还有其他的.
发布于 2015-05-10 22:57:04
您应该使用strtod或相关函数strtof。
#include<stdio.h>
#include <stdlib.h>
int main() {
double d;
char c[25];
char * converted;
for(;;){
printf("\nEnter The Process's Burst Time > 0 : ");
fgets(c, 21, stdin); //Max input is 20.
d = strtod(c,&converted);
if (converted == c){
printf("Conversion unsuccesful");
}
else {
printf("Converted value: %f",d);
}
}
}引用手册页的话:
如果endptr不是空,则在转换中使用的最后一个字符之后指向该字符的指针存储在endptr引用的位置。 如果不执行转换,则返回零,nptr的值存储在endptr引用的位置。
另外,如果输入流太大,我将使用getline而不是gets来避免问题。
https://stackoverflow.com/questions/30157375
复制相似问题