问题描述
下面的程序将字符串转换为长,但根据我的理解,它也返回一个错误。我依靠事实,如果与strtol
成功转换字符串长,那么第二个参数与strtol
应该是平等的为NULL。当我运行下面的应用程序55,我得到以下信息。
./ convertToLong 55
无法转换55长以及吃剩的字符串是:55只要是55
我怎样才能成功地检测出从strtol将错误?在我的应用程序,零是有效的值。
code:
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;静态长parseLong(为const char *海峡);INT主(INT ARGC,字符** argv的)
{
的printf(%S只要是%LD \\ N的argv [1],parseLong(ARGV [1]));
返回0;
}静态长parseLong(为const char *海峡)
{
长_val = 0;
字符*温度; _val =与strtol(STR,&安培;温度,0); 如果(温度!='\\ 0')
的printf(无法%S转换为长以及吃剩的字符串是:%S,STR,温度); 返回_val;
}
您快到了。 温度
本身不会为空,但它会指向一个空字符,如果整个字符串转换,所以你需要取消对它的引用:
如果(*温度!='\\ 0')
The program below converts a string to long, but based on my understanding it also returns an error. I am relying on the fact that if strtol
successfully converted string to long, then the second parameter to strtol
should be equal to NULL. When I run the below application with 55, I get the following message.
./convertToLong 55
Could not convert 55 to long and leftover string is: 55 as long is 55
How can I successfully detect errors from strtol? In my application, zero is a valid value.
Code:
#include <stdio.h>
#include <stdlib.h>
static long parseLong(const char * str);
int main(int argc, char ** argv)
{
printf("%s as long is %ld\n", argv[1], parseLong(argv[1]));
return 0;
}
static long parseLong(const char * str)
{
long _val = 0;
char * temp;
_val = strtol(str, &temp, 0);
if(temp != '\0')
printf("Could not convert %s to long and leftover string is: %s", str, temp);
return _val;
}
You're almost there. temp
itself will not be null, but it will point to a null character if the whole string is converted, so you need to dereference it:
if (*temp != '\0')
这篇关于与strtol的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!