stringstream是c++的一个字符串操作的class
fprintf是c的一个打开文件后,往文件中写入字符的函数(同样的还有printf,sprintf)
#include "stdafx.h"
#include "iostream"
#include "string"
#include "sstream"
using namespace std;
#include "iomanip"
// 填充字符长度,可以用来做数据切分或者类型转化
string i2s(int i, int fill_len = 0, char fill_char = '0')
{
stringstream ss;
ss << setw(fill_len) << setfill(fill_char) << i;
return ss.str();
}
int _tmain(int argc, _TCHAR* argv[])
{
//===============================================================================================
// stringstream的使用
// 1、可以利用i2s来产生或者遍历一些文件
cout << i2s(7, 4, 'c') << endl;
// 2、可以利用stringstream在合适的地方代替sprintf
double f = 0.014;
char str[10];
stringstream ss;
// sprintf(str, "%d", f); // 因为是double,但是使用了"%d"导致一个错误
ss << f;
ss >> str; // 自动推导要转换的类型,这里可以用template把stringstream封装成一个转换函数
cout << str << endl;
// 用完清空一下stringstream
ss.str(""); // 不用clear,是因为clear是ios类继承过来,用于清错误标志的
// 3、切分带有空格的字符串
string s = "my name is zeng raoli";
string tmp;
stringstream ss2;
ss2 << s;
while (1)
{
tmp = "";
ss2 >> tmp;
if (tmp.length() == 0)
{
break;
}
cout << tmp << endl;
}
ss2.str("");
//===============================================================================================
// stringstream的使用
//===============================================================================================
// fprintf的使用:对于c的打开文件太久没用了 试试再用用。。
FILE *out_put_file = NULL;
out_put_file = fopen("1.txt", "w");
if (out_put_file)
{
fprintf(out_put_file, "%s\r\n", "my name is zeng raoli");
}
fclose(out_put_file);
return 0;
}