【发布时间】:2012-12-31 08:47:04
【问题描述】:
这里有一些 C 代码试图阻止用户输入小于 0 或大于 23 的字符或整数。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *input;
char *iPtr;
int count = 0;
int rows;
printf("Enter an integer: ");
scanf("%s", input);
rows = strtol(input, &iPtr, 0);
while( *iPtr != '\0') // Check if any character has been inserted
{
printf("Enter an integer between 1 and 23: ");
scanf("%s", input);
}
while(0 < rows && rows < 24) // check if the user input is within the boundaries
{
printf("Select an integer from 1 to 23: ");
scanf("%s", input);
}
while (count != rows)
{
/* Do some stuff */
}
return 0;
}
我做到了一半,一个小小的俯卧撑将不胜感激。
【问题讨论】:
-
我注意到第三个 scanf 命令有一个明显的问题,应该是 scanf("%i", &rows);但代码仍然被破坏:(
-
您是否考虑过为那些
scanf调用分配内存?就目前而言,他们正在读取保存在未初始化指针 (input) 中的地址,这是未定义的行为。我很确定它的int值是否应该使用%d并扫描到int变量的地址。此外,检查您的scanf调用的返回值,它会告诉您成功获得了多少字段。 -
我把'input'指针改成了数组'char input[100];'
-
你为什么要将它读入文本缓冲区根本?您正在寻找
[0..23]中的整数值,对吗?只需扫描到int并检查是否成功解析和范围内的值,除非您也有兴趣获取一些特殊字符。也许有必要阅读更多关于scanf()的信息? -
我不希望用户输入两种类型的输入,字符和超出范围的整数,这就是我使用文本缓冲区的原因。
标签: c validation user-input