<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">看到很多C++和JAVA新手在用到格式转化的时候总会去百度,所以写一篇常用格式转换的文章,方便大家</span>
c中:
string 转换成其他类型,以doublet型为例
方法一: sscanf和scanf函数相仿
#include <iostream>
#include <string>
#include<cstring>
#include<stdio.h> //sscanf要用到的头文件
using namespace std;
int main()
{
string str="1111.11";
double i;
char buf[10];
strcpy(buf,str.c_str()); //sscanf与scanf类似,都是用于输入的,只是后者以
sscanf(buf,"%lf",&i); //键盘(stdin)为输入源,前者以固定字符串为输入源。
//sscanf的第二个参数是转换格式
std::cout<<"i: "<<i<<endl;
return 0;
}
方法二:atof or atoi等方法和itoa 是作用相反的函数
#include <iostream>
#include <string>
#include<cstring>
#include <stdlib.h> //atof要用到的头文件
using namespace std;
int main()
{
string str="1111.11";
double i;
i=atof(str.c_str()); //atof,atoi,atol,atoll各种类型转化
cout<<i<<endl;
return 0;
}
其他类型转string
方法一:itoa方法和atoi方法是正好相反的,通过函数名字可以看出来,但是这个函数不能跨平台使用,都是只能在windows平台使用的
#include <iostream>
#include <string>
#include<cstring>
#include <stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
char str[234];
int i=111;
itoa(i,str,10); //i是要赋值的value,str是缓冲器地址,10是进制
cout<<str<<endl; //这里有个问题是提到如果是double等类型,litoa函数是可以用的,但是我这里提示没有这个函数
return 0;
}
方法二:用sprintf函数,这个函数和printf的函数的区别在于前者是打印到字符串中,后者打印到命令行上
#include <iostream>
#include <string>
#include<cstring>
#include <stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
char str[234];
int i=111;
int j =222;
sprintf(str,"%d",i); //用法和printf一样
sprintf(str,"%d %d",i,j);
cout<<str;
return 0;
}
JAVA中就简单了
以Int举例
int 转string
int i=111;
1. String.valueOf(i)
2. Integer.toString(i)
3. i+"";
string 转Int
Integer.parseInt(i);