一、为什么要替换?
答:C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更安全的操作。
int n = 9999; char sz[10]; sprintf(sz, "abcdefghijklmn%f", n);
存在的问题:
1、没有检查缓冲区是否溢出,大小是否足够;
2、没有检查格式化符是否匹配;
修改后的代码:
int n = 9999; char sz[10]; stringstream ssTmp; ssTmp << n; ssTmp >> sz;
二、实际应用
1、int 转 string
#include <string> #include <sstream> #include <stdlib.h> using namespace std; int main(int argc, char **argv) { int n = 9999; string str; stringstream ss; ss << n; ss >> str; cout << str << endl; system("pause"); return 0; }
2、int 转 char*
#include "stdafx.h" #include <iostream> #include <string> #include <sstream> #include <stdlib.h> using namespace std; int main(int argc, char **argv) { int n = 9999; char sz[16] = ""; stringstream ss; ss << n; ss >> sz; cout << sz << endl; system("pause"); return 0; }
3、同一个stringstream进行多次转换之前,必须进行clear操作
#include "stdafx.h" #include <iostream> #include <string> #include <sstream> #include <stdlib.h> using namespace std; int main(int argc, char **argv) { int n1 = 9999; int n2 = 99; string strN1, strN2; stringstream ss; ss << n1; ss >> strN1; ss.clear(); ss << n2; ss >> strN2; cout << strN1 << endl; cout << strN2 << endl; system("pause"); return 0; }