整型与字符串转换函数atoi和itoa函数详解

头文件:#include <stdlib.h>

atoi()—ASCII to integer

atoi() 函数用来将字符串转换成整数(int),其原型为:

int atoi (const char * str);

【函数说明】atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到**非数字或字符串结束时(’\0’)**才结束转换,并将结果返回。
【返回值】返回转换后的整型数;如果 str 不能转换成 int 或者 str 为空字符串,那么将返回 0。

atoi()应有举例(有题有代码)

前不久做到一个题目,错误票据–题目详情和代码见:C++蓝桥杯历届试题(附代码)
这道题我就用了atoi()函数读取空格间的每个数字,再用数组记录每个数字出现的次数,从而得到缺失的数字和重复的数字。

itoa—integer to ASCII

itoa()函数将整形转换成字符串

函数说明参照atoi()函数。

其他类似函数

atof—ascii to float–字符串转换成浮点型

atol—ascii to long—字符串转换成长整形

gcvt—浮点型转换成字符串(四舍五入)

strtod—字符串转换成浮点型

strtol—字符串转换成长整形

strtoul–字符串转换成无符号长整形

toascii—将整形转换成合法的ASCII码字符

_ttoi—可以将CString转换成整形

_itot_s—将int转换成char*

atoi()使用的坑

根据以上atoi()函数的原型,我用网上一段代码进行了测试:

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
  int n;
  char *str = "12345.67";
  n = atoi(str);
  printf("string = %s integer = %d\n", str, n);
  return 0;
}

输出是这样:string = 12345.67 integer = 12345
不定义char*也可以用string,要用到c_str()函数

c_str() 以 char* 形式传回 string 内含字符串,如果一个函数要求char*参数,可以使用c_str()方法:
string s = “Hello World!”;
printf("%s", s.c_str()); // 输出 “Hello World!”

函数使用详情见博客:string中c_str()

string s = "3456754321.342";
unsigned int n = atoi(s.c_str());
cout << n << endl; 

替代方法:stringstream

详情见博客:
atoi和itoa之坑------还是用stringstream吧!

发布了54 篇原创文章 · 获赞 26 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43629813/article/details/103494948