使用sprintf()转char型数组
% 印出百分比符号,不转换。
b 整数转成二进位。
c 整数转成对应的 ASCII 字元。
d 整数转成十进位。
f 倍精确度数字转成浮点数。
o 整数转成八进位。
s 整数转成字串。
x 整数转成小写十六进位。
X 整数转成大写十六进位。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n = 30;
char c[20]; //char *c;
//%d十进制
sprintf(c, "%d", n);
cout << c << endl;
//%o八进制
sprintf(c, "%o", n);
cout << c << endl;
//%X大写十六进制
sprintf(c, "%X", n);
cout << c << endl;
//%cACSII字元
sprintf(c, "%c", n);
cout << c << endl;
//%f浮点数转换
float f = 24.678;
sprintf(c, "%f", f);
cout << c << endl;
//%.2f"保留小数点后面两位
sprintf(c, "%.2f", f);
cout << c << endl;
//转换两个数
sprintf(c, "%d-%.2f", n, f);
cout << c << endl;
system("pause");
return 0;
}
输出:
30
36
1E
//注:这里是个特殊符号
24.677999
24.68
30-24.68
注意:在这种方法使用的时候%后面的字符一定要和最初的数据类型一致,否则会报错
2.使用stringstream
#include <iostream>
#include <string>
#include <sstream> //引入stringstream头文件
using namespace std;
int main()
{
stringstream strStream;
int a = 100;
float f = 23.5566;
//int、float类型都可以塞到stringstream中
strStream << a << "----"<< f ;
string s = strStream.str();
cout << s << endl;
system("pause");
return 0;
}
输出:
100----23.5566
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
char a[100]="hhhhhhhhh";
double k=3.1423;
stringstream stream;
stream<<k; //stream赋值k
stream>>a; //a赋值stream
cout<<a<<endl;
return 0;
}
输出:
3.1423
上面的代码通过先给k赋值,再加到a后面实现char数组赋值,要注意如果要重复使用stringstream的话必须要清空,否则会出错。
如果语句里有空格stringstream如何处理
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
string str1("wo hao shuai a a a a ");
string a1,a2,a3,a4;
stringstream stream(str1);
stream>>a1;
stream>>a2;
stream>>a3;
stream>>a4;
cout<<a1<<endl;//输出wo
cout<<a2<<endl;//输出hao
cout<<a3<<endl;//输出shuai
cout<<a4<<endl;//输出a
return 0;
}
由此可见,流中的数据以空格分割开,当给别人传输的时候,一次只穿空格之前的所有数据,并且依次向下。
如果不清空stringstream会造成什么情况
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
int first(111),second(222);
stringstream stream;
stream<<first;
stream>>second;
cout<<second<<endl;//输出111
stream<<2345;
stream>>second;
stream>>k;
cout<<second<<endl;//还是111
return 0;
}
最可怕的其实是这个 如果不用clear(),那么当你再次往流里赋一个值,你猜猜会发生什么?
答案就是,什么也不会发生。你再次用stream给别的变量赋值,他还是会赋原来的那个值。
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
int first(111),second(222);
stringstream stream;
stream<<first;
stream>>second;
cout<<second<<endl;//输出111
stream.clear();
stream<<2345;
stream>>second;
cout<<second<<endl;//2345,correct!
return 0;
}