问题描述
因此,这里的code:
So here's the code:
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 */
}
函数一些位运算创建掩模,但应考虑两个无符号整数b和e,两个非负。问题是如何$负数的对$ pvent用户输入?
当调用函数时使用(-1,0)就开始循环,并与错误shoult退出。
Function creates mask for some bit operations, but should take two unsigned ints b and e, both non-negative. Question is how to prevent user input of negative numbers?When function is called with (-1,0) it start the loop, and shoult exit with error.
推荐答案
您可以只输入一个字符串,检查它是否包含 -
字符,并产生一个如果它的错误。否则你将其转换为一个无符号整数,然后继续上。 (作为那么字符串 strtoul将()
转换阅读是pferred比使用 scanf()的
反正$ P $,特别是而你不知道所有的怪癖的 scanf()的
)
You could just input a string, check if it contains a '-'
character, and yield an error if it does. Else you convert it to an unsigned integer and proceed on. (Reading as a string then converting with strtoul()
is preferred over using scanf()
anyway, especially while you aren't aware of all of the quirks of 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);
这篇关于prevent用户传递负数的函数接受无符号整型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!