zoukankan      html  css  js  c++  java
  • C++ stringstream 简化数据类型转换

    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
    ", buff);
    14     }
    15     else{
    16         printf("err ret:%d
    ", 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
    ", stream.str().c_str());
    13 
    14     stream.str(""); ///重复使用前必须先重置一下
    15     stream << "blog";
    16     stream << ' ';
    17     stream << "is nice";
    18     printf("%s
    ", stream.str().c_str());
    19     return 0;
    20 }

    输出:

    cplusplus关于snprintf有详细的说明: http://www.cplusplus.com/reference/cstdio/snprintf/?kw=snprintf

  • 相关阅读:
    第二阶段冲刺—第三天
    团队测试计划
    第二阶段冲刺—第二天
    第二阶段冲刺—第一天
    评分表
    针对每个组建议的改进
    第二阶段团队绩效评分
    项目总结
    会议2.10
    会议2.9
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/6477197.html
Copyright © 2011-2022 走看看