zoukankan      html  css  js  c++  java
  • stringstream clear与str("")的问题

    一、str与clear函数

    C++Reference对于两者的解释:

    可见:clear()用来设置错误状态,相当于状态的重置;str用来获取或预置内容

    二、区别

    运行下面测试代码:

     1 #include<stdio.h>
     2 #include<iostream>
     3 #include<sstream>
     4 #include<stdbool.h>
     5 #include<string>
     6 using namespace std;
     7 
     8 int main()
     9 {
    10     
    11     string test1;
    12     string test2;
    13     string test3;
    14     stringstream ss;
    15 
    16     for (int j = 0; j<10; j++)
    17     {
    18         ss.clear();
    19         ss.str("");
    20         
    21         ss << j;
    22         test1 = ss.str();
    23         ss >> test2;
    24         test3 = ss.str();
    25         cout << test1<< " "<< test2<< " "<<test3 << endl;
    26     }
    27 
    28     return 0;
    29 }

    (1)注释掉ss.clear()

    输出:

    可发现,不能正确输出

    (2)注释掉ss.str("")

    输出:

    可发现,虽然正确输出,但并没有清空缓冲区

    (3)不注释掉

    输出:

    三、总结

    clear是用来清空stringstream的状态(比如出错等),str("")才能清空内部的缓冲区

    为了保险起见,每次复用stringstream类时,都调用clear(), str(“”) 这两个函数, 把stingstream类复位.

  • 相关阅读:
    经典算法以及案例总结
    supervisor的介绍
    快速排序算法
    mysql 省市联动sql 语句
    前段验证框架 formValidator
    css 之!important
    js 倒计时
    js 设置url 参数值
    java 获取指定日期
    js 日期控件laydate使用
  • 原文地址:https://www.cnblogs.com/lfri/p/9364275.html
Copyright © 2011-2022 走看看