当前位置:   article > 正文

C++编程语言中stringstream类介绍

stringstream

本文主要介绍C++编程语言中stringstream类的相关知识,同时通过示例代码介绍stringstream类的使用方法。

1 概述

<sstream>定义了三个istringstreamostringstreamstringstream,分别用来进行流的输入、输出和输入输出操作。本文以stringstream为主,介绍流的输入和输出操作。

<sstream>主要用来进行数据类型转换,由于<sstream>使用string对象来代替字符数组(snprintf 方式),避免了缓冲区溢出的危险,而且,因为传入参数和目标对象的类型会被自动推导出来,所以也不存在错误的格式化符号的问题。简单说,相比C编程语言库的数据类型转换,<sstream>更加安全、自动和直接。

2 示例代码

2.1 数据类型转换

此处展示一份示例代码,介绍将int类型转换为string类型的过程。

示例代码(stringstream_test1.cpp)的内容如下:

  1. #include <string>
  2. #include <sstream>
  3. #include <iostream>
  4. #include <stdio.h>
  5. using namespace std;
  6. int main()
  7. {
  8. stringstream sstream;
  9. string strResult;
  10. int nValue = 1000;
  11. // 将int类型的值放入输入流中
  12. sstream << nValue;
  13. // 从sstream中抽取前面插入的int类型的值,赋给string类型
  14. sstream >> strResult;
  15. cout << "[cout]strResult is: " << strResult << endl;
  16. printf("[printf]strResult is: %s\n", strResult.c_str());
  17. return 0;
  18. }

编译并执行上述代码,结果如下:

2.2 多个字符串拼接

本示例介绍在stringstream中存放多个字符串,实现多个字符串拼接的目的(其实完全可以使用string类实现),同时,介绍stringstream类的清空方法。

示例代码(stringstream_test2.cpp)的内容如下:

  1. #include <string>
  2. #include <sstream>
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. stringstream sstream;
  8. // 将多个字符串放入 sstream 中
  9. sstream << "first" << " " << "string,";
  10. sstream << " second string";
  11. cout << "strResult is: " << sstream.str() << endl;
  12. // 清空 sstream
  13. sstream.str("");
  14. sstream << "third string";
  15. cout << "After clear, strResult is: " << sstream.str() << endl;
  16. return 0;
  17. }

编译并执行上述代码,结果如下:

从上述代码执行结果能够知道:

  • 可以使用str()方法,将stringstream类型转换为string类型;
  • 可以将多个字符串放入stringstream中,实现字符串的拼接目的;
  • 如果想清空stringstream,必须使用“sstream.str("");”方式;clear()方法适用于进行多次数据类型转换的场景。详见示例2.3。

2.3 stringstream的清空

清空stringstream有两种方法:clear()方法以及str("")方法,这两种方法对应不同的使用场景。str("")方法的使用场景,在上面的示例中已经介绍过了,这里介绍clear()方法的使用场景。

示例代码(stringstream_test3.cpp)的内容如下:

  1. #include <sstream>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. stringstream sstream;
  7. int first, second;
  8. // 插入字符串
  9. sstream << "456";
  10. // 转换为int类型
  11. sstream >> first;
  12. cout << first << endl;
  13. // 在进行多次类型转换前,必须先运行clear()
  14. sstream.clear();
  15. // 插入bool值
  16. sstream << true;
  17. // 转换为int类型
  18. sstream >> second;
  19. cout << second << endl;
  20. return 0;
  21. }

编译并执行上述代码,结果如下:

注意:在本示例涉及的场景下(多次数据类型转换),必须使用clear()方法清空stringstream,不使用clear()方法、或者使用str("")方法,都不能得到正确的数据类型转换结果。下图分别是未使用clear()方法、使用str("")方法代替clear()方法时的运行结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/735987
推荐阅读
  

闽ICP备14008679号