C ++中的atoi函数 [英] atoi function in C++

查看:117
本文介绍了C ++中的atoi函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我遇到了C ++函数

Hi,

I came across C++ function

atoi

,该函数返回给定字符串的整数表示.

如果我将"987"传递给此函数,它将以整数形式返回987.

在MSDN中,该函数在失败时返回0 .如果我将"0"传递给该函数怎么办?
它会以整数形式返回0 .....我应该将其视为错误代码还是已转换的值:(

, This function returns integer representation of given string.

If i pass "987" to this function , it will return 987 as integer.

In MSDN it is written that, this function returns 0 on failure. What if i pass "0" to this function ??

it will return 0 as integer .....Should i treat it as a ERRORCODE or converted value :(

推荐答案

该函数返回0时,您必须检查一下自己如果字符串是有效数字(解析可选的前导空格,可选符号和"0"字符,后跟一个NULL字节).

如果需要高级错误检查,则可以使用 strtol() [ ^ ]函数.
When the function returns 0, you must check yourself if the string is a valid number (parse for optional leading white spaces, optional sign, and the ''0'' character followed by a NULL byte).

If you need advanced error checking, you may use the strtol() [^] function.


您可以使用errno全局变量.如果不等于0,则说明存在错误,您可以检查它是什么(溢出或其他转换错误)
如果atoi返回0且errno == 0,则可以确保转换成功完成

像这样的东西:
You can use errno global variable. If it is not equal to 0 then there was error and you can check what it was (overflow or other conversion error)
In the case atoi returns 0 and errno == 0 you can be sure that conversion was finished successfully

Something like this:
int val;

val = atoi("bad value");
if (errno != 0)
{
   printf("Error");
}
else
{
   // Do something with val
}


这篇关于C ++中的atoi函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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