C++標准庫中的<sstream>提供了比ANSI C的<stdio.h>更高級的一些功能,即單純性、類型安全和可擴展性。
在C++中經常會使用到snprintf來格式化一些輸出。為了正確地完成這個任務,必須確保證目標緩沖區有足夠大空間以容納轉換完的字符串。此外,還必須使用正確的格式化符。如果使用了不正確的格式化符,會導致非預知的后果。
1. snprintf需要注意buff的大小,以及對返回值的判斷。
1 #include <stdio.h> 2 3 int main(){ 4 char *gcc= "gcc"; 5 int no = 1; 6 7 ///調節char數組的大小可以看到不同的輸出。 8 ///因此一定要注意buff的大小, 以及snprintf的返回值 9 char buff[10]; 10 int ret = 0; 11 ret = snprintf(buff, sizeof(buff), "%s is No %d", gcc, no); 12 if (ret >= 0 && ret < sizeof(buff)){ 13 printf("%s\n", buff); 14 } 15 else{ 16 printf("err ret:%d\n", ret); 17 } 18 return 0; 19 }
2. 使用stringstream
<sstream>庫定義了三種類:istringstream、ostringstream和stringstream,分別用來進行流的輸入、輸出和輸入輸出操作。
使用stringstream比snprintf更加省心。
std::stringstream比std::string使用更加靈活,支持各種格式。
1 #include <stdio.h> 2 #include <sstream> 3 4 int main(){ 5 char *gcc= "gcc"; 6 int no = 1; 7 8 std::stringstream stream; 9 stream << gcc; 10 stream << " is No "; 11 stream << no; 12 printf("%s\n", stream.str().c_str()); 13 14 stream.str(""); ///重復使用前必須先重置一下 15 stream << "blog"; 16 stream << ' '; 17 stream << "is nice"; 18 printf("%s\n", stream.str().c_str()); 19 return 0; 20 }
輸出:
cplusplus關於snprintf有詳細的說明: http://www.cplusplus.com/reference/cstdio/snprintf/?kw=snprintf