一、str与clear函数

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

stringstream clear与str("")的问题

stringstream clear与str("")的问题

可见: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()

输出:

stringstream clear与str("")的问题

可发现,不能正确输出

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

输出:

stringstream clear与str("")的问题

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

(3)不注释掉

输出:

stringstream clear与str("")的问题

三、总结

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

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

 

相关文章:

  • 2021-05-23
  • 2021-09-15
  • 2022-02-19
  • 2021-06-20
  • 2021-10-23
  • 2021-08-23
  • 2022-02-11
  • 2021-11-17
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-20
  • 2021-09-15
  • 2022-12-23
  • 2021-08-25
相关资源
相似解决方案