阻止用户将负数传递给接受unsigned int的函数

zub*_*rgu 4 c negative-number unsigned-integer

所以这是代码:

int create_mask(unsigned b, unsigned e)
{
  unsigned int mask=1;

  if(b<e || b<0 || e<0)
  {
    printf("Wrong values, starting bit can't be smaller than ending.\n");
    printf("Both got to be >= 0.\n");
    exit(EXIT_FAILURE);
  }
  while(b>0)
  {
    printf("%u\n", b);
    mask<<=1;
    if(b>e)
      mask|=1;
    b--;
  }

  return ~mask; /* negates mask for later purpose that is clearing corresponding bits */
}
Run Code Online (Sandbox Code Playgroud)

函数为某些位操作创建掩码,但应该采用两个无符号整数b和e,两者都是非负数.问题是如何防止用户输入负数?当用(-1,0)调用函数时,它启动循环,并且错误地退出.

小智 5

您可以只输入一个字符串,检查它是否包含一个'-'字符,如果出现则产生错误.否则,将其转换为无符号整数并继续.(作为一个字符串读取然后转换strtoul()是优先使用scanf(),尤其是当你不知道所有的怪癖时scanf().)

char buf[LINE_MAX];
fgets(buf, sizeof buf, stdin);

if (strchr(buf, '-') != NULL) {
    fprintf(stderr, "input must be non-negative!\n");
    exit(-1);
}

unsigned int n = strtoul(buf, NULL, 0);
Run Code Online (Sandbox Code Playgroud)