【问题标题】:Validating the scanf entry验证 scanf 条目
【发布时间】:2013-12-17 00:36:45
【问题描述】:

我正在考虑对这个循环进行一些验证,以确保 entry 大于或等于且小于或等于 1024。

我试过了

if(scanf("%d", &records[*rCount].source) == 1 && &records[*rCount].source >= 1 && &records[r*Count].source <= 1024)

但这会停止所有条目的工作。

下面是我目前正在使用的 do while 循环,谢谢。

do{
        puts("What is the source of this packet?: ");
        if(scanf("%d", &records[*rCount].source) == 1){  //if correct insert the record at the index
            valid=1;                                //determined by rCount(the current     record count passed to addRecord
        }
        else{
            valid = 0;
            getchar();
            puts("\nNot a valid input");
        }

    }while(valid!=1);

【问题讨论】:

  • 为什么要在这里使用 getchar?
  • r*Count 是错字吧?
  • @rullof 也许是为了赶上换行符 ('\n')。
  • getchar 会在用户输入字符时停止循环。
  • @BitFiddlingCodeMonkey 所以他应该使用循环:while(getchar()!='\n');

标签: c validation scanf


【解决方案1】:

您在读取所需变量的地址后对其进行测试。

你将&amp;records[*rCount].sourcerecords[*rCount].source 的地址(注意开头多余的和号)传递给scanf,所以函数将从标准输入读取的内容保存到这个地址。之后,您希望将变量值而不是其地址与您的限制进行比较。

您更正后的if 将是:

if (scanf("%d", &records[*rCount].source) == 1
    && records[*rCount].source >= 1
    && records[*rCount].source <= 1024)
{
    // do stuff...
}

【讨论】:

  • 是的,可能。感谢 Bit Fiddleing Code Monkey 的指出和 Michael Pryor 的编辑。
猜你喜欢
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-19
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多