c++将整数转换为字符串和字符串转化为数字

整数转字符串
1.使用itoa 需要用到的头文件: #include <stdlib.h>

# include <stdio.h>
# include <stdlib.h>
void main (void)
{
int num = 100;
char str[25];
itoa(num, str, 10);
printf("The number 'num' is %d and the string 'str' is %s. \n" ,
num, str);
}

itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用 的基数。.

itoa并不是一个标准的C函数,它是Windows特有的.

2.sprintf
如果要写跨平台的程序,请用sprintf。是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似:
char str[255];
sprintf(str, “%x”, 100); //将100转为16进制表示的字符串。

3.sstream

#include <string>
#include <sstream>
#include <iostream> 
using namespace std;
int main(){
    double a = 123.32;
    string res;
    stringstream ss;
    ss << a;
    ss >> res;//或者 res = ss.str();
    cout<<res; 
    return 0;
}

字符串转数字 需要用到的头文件: #include <stdlib.h>
1.atoi

#include <ctype.h>
#include <stdio.h>
int atoi (char s[]);
int main(void )
{
char s[100];
gets(s);
printf("integer=%d\n",atoi(s));
return 0;
}
int atoi (char s[])
{
int i,n,sign;
for(i=0;isspace(s[i]);i++)//跳过空白符;
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]==' -')//跳过符号
  i++;
for(n=0;isdigit(s[i]);i++)
       n=10*n+(s[i]-'0');//将数字字符转换成整形数字
return sign *n;
}

2.sscanf

 char str[] = "15.455";
     int i;
     float fp;
     sscanf( str, "%d", &i ); // 将字符串转换成整数 i = 15
     sscanf( str, "%f", &fp ); // 将字符串转换成浮点数 fp = 15.455000

3.sstream

    stringstream sstr(str);
    int x;
    sstr >> x;(即从sstr中提取数据)

处理大量数据转换速度较慢。stringstream不会主动释放内存,如果要在程序中用同一个流,需要适时地清除一下缓存(用stream.str("")和stream.clear()).

猜你喜欢

转载自blog.csdn.net/ywh15387127537/article/details/88042783