解析整数而不在C中附加字符 [英] parse integer without appending char in C
问题描述
我想解析一个整数,但我下面的代码也接受像3b"这样的字符串,它以数字开头但附加了字符.我如何拒绝这样的字符串?
I want to parse an integer but my following code also accepts Strings like "3b" which start as a number but have appended chars. How do I reject such Strings?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
if(argc==2 && sscanf(argv[1], "%d", &n)==1 && n>0){
f(n);
return 0;
}
else{
exit(EXIT_FAILURE);
}
}
推荐答案
对于你的问题,你可以使用 #include
strtol()
函数代码>库.
For your problem, you can use strtol()
function from the #include <stdlib.h>
library.
如何使用 strtol
(教程要点中的示例代码一>)
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[30] = "2030300 This is test";
char *ptr;
long ret;
ret = strtol(str, &ptr, 10);
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
return(0);
}
在strtol
中,它扫描str
,将单词存储在一个指针中,然后是被转换的数字的基数.如果基数在 2 到 36 之间,则用作数字的基数.但我建议将 0 放在 10 所在的位置,这样它就会自动选择正确的数字.其余的存储在 ret
中.
Inside the strtol
, it scans str
, stores the words in a pointer, then the base of the number being converted. If the base is between 2 and 36, it is used as the radix of the number. But I recommend putting zero where the 10 is so it will automatically pick the right number. The rest is stored in ret
.
这篇关于解析整数而不在C中附加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!