我写了一个 get_float()
函数,它应该只接受有效的浮点值,只有正值,并且该值必须大于零且小于 FLT_MAX: (FLT_MAX > length > 0)
。
除一种情况外,此功能在所有情况下都能发挥作用:
~$ gcc -Wall -std=c11 -o ValidatedFload ValidatedFload.c ~$ ./ValidatedFload Please enter a length: asd [ERR] Invalid length. Please enter a length: -1 [ERR] Invalid length. Please enter a length: 0 [ERR] Invalid length. Please enter a length: 4.fuu [OK] Valid length.
As you can see 4.fuu is not a valid input, therefore the [ERR]-message should appear! My function is the following:
float get_float()
{
const float FLT_MAX = 100.0; // Max size of a triplet length
float length = 0; // Temporary saves the triangle lengths
char loop = 'y'; // Boolean value for the read-in-loop
while (loop == 'y') {
printf("Please enter a length: ");
scanf("%f", &length);
if ((length > 0) && (length < FLT_MAX)) {
printf("[OK] Valid length.\n");
loop = 'n';
}
else{
printf("[ERR] Invalid length.\n");
// Flushes the input buffer, to prevent an endless loop by
// wrong input like '5.fuu' or '1.23bar'
while ((getchar()) != '\n');
}
}
return length;
}
我非常感谢任何帮助、链接、引用和提示!
最佳答案
非常感谢 EdHeal,我能够通过检查 scanf() 返回值来解决问题:
float get_float()
{
const float FLT_MAX = 100.0; // Max size of a triplet length
float length = 0; // Temporary saves the triangle lengths
char loop = 'y'; // Boolean value for the read-in-loop
char term;
while (loop == 'y') {
printf("Please enter a length: ");
if (scanf("%f%c", &length, &term) != 2 || term != '\n') {
printf("[ERR] Invalid length.\n");
while ((getchar()) != '\n'); // Flushes the scanf() input buffer
}
else {
if ((length > 0) && (length < FLT_MAX)) {
printf("[OK] Valid length.\n");
loop = 'n';
}
else{
printf("[ERR] Invalid length.\n");
}
}
}
return length;
}
关于c - float 应该只接受正确的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872334/