C++ stringstream 简化数据类型转换

来源:互联网 发布:阿里云 李津 编辑:程序博客网 时间:2024/06/05 14:18

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

 

0 0
原创粉丝点击