atoi(string到int)
来源:互联网 发布:潮汕麻将源码 编辑:程序博客网 时间:2024/06/11 20:55
atoi
<cstdlib>
int atoi ( const char * str );
Convert string to integer
Parses the C string str interpreting its content as an integral number, which is returned as an int value.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initialplus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because eitherstr is empty or it contains only whitespace characters, no conversion is performed.
Parameters
- str
- C string beginning with the representation of an integral number.
Return Value
On success, the function returns the converted integral number as an 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, INT_MAX or INT_MIN is returned.
Example
/* atoi example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char szInput [256];
printf ("Enter a number: ");
fgets ( szInput, 256, stdin );
i = atoi (szInput);
printf ("The value entered is %d. The double is %d.\n",i,i*2);
return 0;
}
Output:
Enter a number: 73 The value entered is 73. The double is 146.那我们应该怎么用呢?看下面这个例子:
比如我们要从文件中读取345+234;并且进行计算,没有空格。
可能我们会想到用内核格式化,在+号,这种方法是可行的,但是如果式子换成345*234,就悲剧了。。
所以我们必须采用逐字符的读法,然后将数字字符组合成int。
string temp;//temp用来保存数字字符
getline(in_file, infix);
for(int i = 0; i < (int) infix.size(); i++)
{
if(isalnum(infix[j]))//如果是数字字符,需要cctype头文件
{
temp += infix[j];//追加到temp
}
else
{
cout << atoi(temp) << endl;//遇到其他非数字字符时说明读取结束,转换输出
}
}
当然了,这只是我的一种方法,相信大家有更好的方法。
- atoi(string到int)
- atoi 实现 + string转int + int转string
- atoi char and string to int
- LeetCode 8 String to Integer (atoi)(转换到整型)
- Int到String 转换
- [C++]LeetCode 8:String to Integer (atoi)(字符串转int)
- 【LeetCode008-009算法/编程练习C++】string转int(atoi),判断数字是否是回文
- 字符串string转整数int 实现自己的atoi函数
- leetcode 412 to_string 转string atoi(str.c_str())转int
- LeetCode 08:string to int(atoi)(C++实现)
- 关于int 到 string 类型
- int到string的转换
- string 到 int的转换
- 实现atoi——从char*到int的转换
- c++ int to string(整型到字符串)
- c++ int to string(整型到字符串)
- c++ int to string(整型到字符串)
- 从 int 到 string 的几种方法(C++)
- 关于论坛建设相关细节设计问题归纳
- Python 打油诗
- Spring依赖注入
- Java程序题2
- 在Excel中禁止删除工作表
- atoi(string到int)
- 待写
- 深入浅出DirectShow Filter(二)
- Java程序题3
- Linux USB 鼠标驱动程序解析
- 强大的内核格式化(incore formatting)
- Hibernate关联关系映射_引言
- SCRIPT5007: 无法获取属性“getElementsByTagName”的值: 对象为 null 或未定
- PHP获取时间比实际时间少--解决