C语言的atoi和C++的to_string

to_string int to string将其他型转换成字符串型
atoi ascii to integer是把字符串转换成整型数的一个函数

to_string

#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string

int main ()
{
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
  std::cout << perfect << '\n';
  return 0;
}

把整型数据28(函数内部可进行运算)和后面的字符串” is a perfect number”进行合并

pi is 3.141593
28 is a perfect number

atoi

#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */

int main ()
{
  int i;
  char buffer[256];
  printf ("Enter a number: ");
  fgets (buffer, 256, stdin);
  i = atoi (buffer);
  printf ("The value entered is %d. Its double is %d.\n",i,i*2);
  return 0;
}
Enter a number: 73
The value entered is 73. Its double is 146.

额外拓展了解即可

1.int/float to string/array:
● ultoa():将无符号长整型值转换为字符串。
● gcvt():将浮点型数转换为字符串,取四舍五入。
● ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
● fcvt():指定位数为转换精度,其余同ecvt()。

除此外,还可以使用sprintf系列函数把数字转换成字符串,其比itoa()系列函数运行速度慢
2. string/array to int/float
C/C++语言提供了几个标准库函数,可以将字符串转换为任意类型(整型、长整型、浮点型等)。
● atof():将字符串转换为双精度浮点型值。
● atol():将字符串转换为长整型值。
● strtod():将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字。
● strtol():将字符串转换为长整值,并报告不能被转换的所有剩余数字。
● strtoul():将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字。

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/81267720