我想编写一个代码来确保用户只输入1位数。如果用户输入类似" 0 1 3"我希望我的程序读取错误消息,我不知道该怎么做。任何人都知道如何处理这个问题?如果用户输入一组中间有空格的数字,我当前的代码只会接收第一个数字。
请参阅下面的代码。谢谢:D
//Prompt the user to enter the low radius with data validation
printf("Enter the low radius [0.0..40.0]: ");
do
{
ret = scanf("%lf", &lowRadius);
//type validation
if (ret != 1)
{
int ch = 0;
while (((ch = getchar()) != EOF) && (ch != '\n'));
printf("Wrong input. Please enter one numerical value: ");
}
//range validation
else if((lowRadius < 0 || lowRadius > 40))
{
printf("Incorrect value. Please enter in range 0-40: ");
}
else break;
} while ((ret != 1) || (lowRadius < 0 || lowRadius > 40));//end while lowRadius
答案 0 :(得分:2)
如果您将该行读入字符串,然后对其进行分析,则可以避免挂起未提供输入的问题。您已经完成了大部分工作,但这显示了如何捕获过多的输入。它的工作原理是在double
之后扫描一个字符串以获取更多输入。来自sscanf
的返回值会告诉您是否存在,因为它返回成功扫描的项目数。
#include <stdio.h>
#include <stdlib.h>
void err(char *message)
{
puts(message);
exit(1);
}
int main(void)
{
double lowRadius = 0.0;
char inp[100];
char more[2];
int conv;
if(fgets(inp, sizeof inp, stdin) == NULL) {
err("Input unsuccesful");
}
conv = sscanf(inp, "%lf %1s", &lowRadius, more); // conv is number of items scanned
if(conv != 1) {
err("One input value is required");
}
if(lowRadius < 0.0 || lowRadius > 40.0) {
err("Number out of range");
}
printf("%f\n", lowRadius);
return 0;
}
我不确定您对单个数字的规定,因为它不允许输入您的最大值。
答案 1 :(得分:0)
阅读整行并将其转换为strtod
。
答案 2 :(得分:0)
亚历山大有正确的方法,但没有提供太多细节。以下是我将如何操作,使用getline()读取输入,然后使用strspn()和strtod()来解析读取的输入。如果你不熟悉使用指针,这将很难理解 - 但如果你正在学习C,你最终会到达那里:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
double lowRadius;
char *lineptr = NULL;
size_t n;
char *startptr;
char *endptr;
char *ws = " \t\n"; /* possible whitespace characters */
printf("Enter the low radius [0.0..40.0]: ");
while(1) {
/* free lineptr if set - neeeded if we iterate on error input */
if( lineptr ) {
free(lineptr);
lineptr = NULL;
}
/* now read a line of input */
while( getline(&lineptr, &n, stdin) == -1 ) {
/* error returned, just retry */
continue;
}
/* skip over any leading whitespace */
startptr = lineptr + strspn(lineptr,ws);
/* Now try to convert double */
lowRadius = strtod(startptr, &endptr);
if( endptr==startptr || endptr[strspn(endptr,ws)] != 0 ) {
/* either no characters were processed - e.g., the
line was empty, or there was some non-whitespace
character found after the number. */
printf( "Wrong input. Please enter one numerical value: ");
} else if( (lowRadius < 0.0) || (lowRadius > 40.0) ) {
printf( "Incorrect value. Please enter in range 0-40: " );
} else {
if( lineptr ) free(lineptr);
break;
}
}
printf( "value entered was %lf\n", lowRadius );
}