stringstream、fprintf

来源:互联网 发布:叶枫淘宝大学免费课程 编辑:程序博客网 时间:2024/06/07 16:20

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在合适的地方代替sprintfdouble f = 0.014;char str[10];stringstream ss;//sprintf(str, "%d", f);// 因为是double,但是使用了"%d"导致一个错误ss << f;ss >> str;// 自动推导要转换的类型,这里可以用template把stringstream封装成一个转换函数cout << str << endl;// 用完清空一下stringstreamss.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;}


0 0