请我是编程新手。我刚开始使用c ++,我得到了一个使用stringstream的地方。这些东西让我感到困惑。请有人帮助我。
答案 0 :(得分:6)
至于你的问题,你知道如何使用std::cout
来编写输出吗?你知道如何使用std::cin
来读取输入吗?然后,您就知道了使用任何流所需的一切,包括std::stringstream
(及其output-only和input-only兄弟姐妹。)
区别在于字符串流要写入(或读取)字符串而不是控制台或终端。
例如,假设您想要从其他一些文本和一些数字构造一个字符串,那么您可以使用std::ostringstream
:
std::string my_name = "Joachim";
int my_age = 42;
std::ostringstream ostr;
ostr << "My name is " << my_name
<< " and my age is " << my_age;
std::string str = ostr.str(); // Get the string constructed above
std::cout << str << '\n'; // Outputs "My name is Joachim and my age is 42"
输入字符串流可能不像输出字符串流那样频繁使用,但可以通过从输入文件流中读取一行到{{1}来逐行地解析文件中的输入。然后使用输入字符串流来提取数据,就像你使用的那样std::string
。
答案 1 :(得分:0)
除了Joachim Pileborg的解释之外,我想补充一些内容
stringstream是内部的typedef "basic_stringstream<char>"
。
typedef basic_stringstream<char> stringstream;
使用Stream类对字符串进行操作。
此类的对象使用包含一系列字符的字符串缓冲区。这个字符序列可以使用成员str。
直接作为字符串对象访问可以使用输入和输出流上允许的任何操作从流中插入和/或提取字符。
有公共成员职能。
std::stringstream::stringstream
default (1)
explicit stringstream (ios_base::openmode which = ios_base::in | ios_base::out);
initialization (2)
explicit stringstream (const string& str,
ios_base::openmode which = ios_base::in | ios_base::out);
示例:
#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;
}
Output:
foo: 100
bar: 200
总而言之,字符串流基本上用于对字符串执行输入/输出操作(由“std”提供很多功能,否则难以编程)。