[转]c++标准库sstream的用法
2020-05-08 04:13
1071 查看
<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。
-
#include <string> // std::string
-
#include <iostream> // std::cout
-
#include <sstream> // std::istringstream
-
int main () {
-
std::istringstream iss;
-
std::string strvalues = "32 240 2 1450";
-
iss.str (strvalues);
-
for (int n=0; n<4; n++)
-
{
-
int val;
-
iss >> val;
-
std::cout << val << '\n';
-
}
-
std::cout << "Finished writing the numbers in: ";
-
std::cout << iss.str() << '\n';
-
return 0;
-
// swapping ostringstream objects
-
#include <string> // std::string
-
#include <iostream> // std::cout
-
#include <sstream> // std::stringstream
-
int main () {
-
std::stringstream ss;
-
ss << 100 << ' ' << 200;
-
int foo,bar;
-
ss >> foo >> bar;
-
std::cout << "foo: " << foo << '\n';
-
std::cout << "bar: " << bar << '\n';
-
return 0;
-
}
leetcode上有一道题目,利用stringstream可以很好地解决:leetcode
-
class Solution {
-
public:
-
int countSegments(string s) {
-
stringstream input(s);
-
int count = 0;
-
string temp;
-
while (input>>temp)
-
{
-
count++;
-
}
-
return count;
-
}
-
};
---------------------
作者:svdalv
来源:CSDN
原文:https://blog.csdn.net/ns708865818/article/details/53557957
版权声明:本文为作者原创文章,转载请附上博文链接!
相关文章推荐
- c++标准库sstream的用法
- C++标准库Vector & Iterator用法
- C++标准库:bitset 用法整理
- C++标准库:Map用法
- C++标准库:bitset 用法整理
- C++标准库Vector & Iterator用法
- C++标准库vector类(简单用法记录)
- C++标准库类型string用法小结
- C++标准库:bitset 用法整理
- C++标准库中sstream和strstream的区别
- sstream的用法
- C++标准库:bitset 用法整理 (来自网易 happyboy200032的博客)
- sstream用法
- C++标准库:bitset 用法整理
- C++标准库中排序函数sort的用法
- C++标准库:bitset 用法整理
- C++标准库函数swap的用法
- sstream和strstream的用法
- c++标准库中vector数组遍历时的用法
- C++标准库---for_each()用法及回返值