【问题标题】:Understanding stringstream [closed]了解字符串流 [关闭]
【发布时间】:2017-07-31 03:42:13
【问题描述】:
我以前从未使用过 stringstream,并获得了示例代码,但没有解释代码中发生了什么。如果有人可以解释每一行的目的,那就太好了。我查看了多个地方,但似乎无法确定第二行。
#include <sstream> // i know this line includes the file
stringstream ss(aStringVariable);// this line in particular
ss >> aVariable;
getline(ss, stringVariable2HoldValue, ‘|’);
【问题讨论】:
标签:
c++
string
c++11
sstream
【解决方案1】:
std::stringstream 的构造函数接受 std::string 作为参数并使用该值初始化流。
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::stringstream ss("foo bar");
std::string str1, str2;
ss >> str1 >> str2;
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
}
此代码使用值"foo bar" 初始化stringstream、ss,然后将其读入两个字符串str1 和str2,这与从文件中读取或std::cin.