如何确保 strtol() 已成功返回? [英] How do I make sure that strtol() have returned successfully?

查看:28
本文介绍了如何确保 strtol() 已成功返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档:

成功时,函数返回转换后的整数作为长整数值.如果无法执行有效的转换,则为零值被返回.如果正确的值超出范围可表示的值,返回 LONG_MAX 或 LONG_MIN,全局变量 errno 设置为 ERANGE.

On success, the function returns the converted integral number as a long int value. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, LONG_MAX or LONG_MIN is returned, and the global variable errno is set to ERANGE.

考虑 strtol(str, (char**)NULL, 10); 如果 str"0\0" 怎么知道如果函数失败或只转换了带有 "0" 数字的字符串?

Consider strtol(str, (char**)NULL, 10); if str is "0\0" how to know if the function failed or only has converted the string with "0" number?

推荐答案

如果你想进行错误检查,你需要传递一个真实的指针地址,这样你就可以区分 "0" 和与 "pqr" 产生的 0 值相似:

You need to pass a real pointer address if you want error checking, so you can distinguish 0 values arising from "0" and similar from 0 values arising from "pqr":

char *endptr;
errno = 0;
long result = strtol(str, &endptr, 10);
if (endptr == str)
{
    // nothing parsed from the string, handle errors or exit
}
if ((result == LONG_MAX || result == LONG_MIN) && errno == ERANGE)
{
    // out of range, handle or exit
}
// all went fine, go on

这篇关于如何确保 strtol() 已成功返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆