我是C语言的新手,但我了解C#。在C#中,我可以使用TryParse来确保用户输入正确的数据类型。
下面是我为C编写的基本代码:
int shallowDepth;
do
{
printf ("\nEnter a depth for the shallow end between 2-5 feet: ");
scanf ("%d", &shallowDepth);
if (shallowDepth < 2 || shallowDepth > 5)
{
printf("\nThe depth of the shallow end must be between 2-5 feet.");
}
}
while (shallowDepth < 2 || shallowDepth > 5);
问题是,如果我输入字符,比如"asdf“,程序就会变得疯狂,并重复地说”输入2-5英尺之间浅端的深度:“。我不确定为什么会发生这种情况,但一定是因为它需要一个int,而我传递的是字符。
那么,在尝试将数据存储在变量中之前,如何验证用户输入的数据是int类型呢?谢谢。
发布于 2014-02-06 08:18:56
这是因为使用%d
时,scanf
将拒绝接触任何看起来不像数字的内容,并将文本留在缓冲区中。下一次,它将再次到达相同的文本,依此类推。
我建议您现在放弃scanf
,尝试像fgets
这样的函数,然后再尝试strtoXXX
家族中的一个函数,比如strtoul
或strtoumax
。这些函数具有定义良好的报告错误的方式,您可以很容易地提示用户输入更多文本。
例如,您可以这样做:
char str[LENGTH];
long x;
if (!fgets(str, sizeof str, stdin)) {
/* Early EOF or error. Either way, bail. */
}
x = strtol(line, NULL, 10);
在这一点上,您可以使用您的号码,但请注意:
strtol
指定一个指针来填充,它将指向第一个不可接受的字符long
,则strtol
将设置errno = ERANGE
。如果您计划测试此errno = 0
,则必须在strtol
之前设置
发布于 2014-02-06 08:21:18
如果你想使用scanf
,你之前不能测试它。但是你不需要太多!
在您的代码中,如果用户没有输入数字(或以数字开头的内容),scanf
将返回0,因为它返回它可以读取的参数数量。因此,您需要检查scanf
的返回值,以检查是否可以读取任何内容。其次,您需要移除仍在吹风机中的所有东西。您可以使用类似于以下内容的内容:
while(getchar()!='\n');
如果您还想处理文件,那么您也应该在那里捕获EOF
。
发布于 2014-02-06 10:34:23
int shallowDepth;
int invalid;
do {
int stat;
invalid = 0;
printf ("\nEnter a depth for the shallow end between 2-5 feet: ");
stat = scanf ("%d", &shallowDepth);
if(stat != 1){
invalid = 1;
while(getchar() != '\n');//clear stdin
} else if (shallowDepth < 2 || shallowDepth > 5){
invalid = 1;
printf("\nThe depth of the shallow end must be between 2-5 feet.");
}
}while (invalid);
https://stackoverflow.com/questions/21591484
复制相似问题