我要保持这个问题非常简单.我正在学习C++,而且我遇到过串流.我知道它们的主要用途是将变量输入到它们中,以便稍后可以使用str()作为字符串输出它们保存的值.我的问题是 - 这有什么意义?这听起来像是一种非常奇特的方式,只需使用+运算符连接字符串对象中的一堆变量.它是否比它更多还是它只是因为它混淆了新手而导致他们考试不及格?
好吧,一个问题是你不能"使用+运算符"连接字符串中的一堆变量"(只有其他字符串或char*).
那么,您如何将所有对象转换为字符串?与Java不同,C++没有任何to_string()成员约定.另一方面,每个对使用iostream感兴趣的类都会定义流插入器(std::ostream& operator<<(std::ostream& os, const MyClass& foo)也许是std::istream& operator>>(std::istream& os, MyClass& foo).)
因此,您使用流插入器将对象转换为文本.有时您不想写入控制台或文件,而是希望将其存储为字符串.
此外,使用iostream框架可以让您使用操纵器来控制精度,宽度,数字基础等,而不是在构造字符串时尝试手动执行所有操作.
现在,这并不是说stringstream解决方案是理想的:实际上,存在很多库以更好地完成相同类型的任务(至少包括Boost.Format,Boost.Convert,Boost.Lexical_Cast和Boost.Spirit)在Boost.)
如果你有:
int a = 3;
std::string str = "hello";
MyObject obj;
Run Code Online (Sandbox Code Playgroud)
然后:
std::string concat = a + str + obj;
std::string objstr = obj;
Run Code Online (Sandbox Code Playgroud)
不起作用,而:
std::stringstream stream;
stream << a << str << obj;
std::string concat = stream.str();
std::stringstream stream2;
stream2 << obj;
std::string objstr = stream2.str();
Run Code Online (Sandbox Code Playgroud)
会工作(至少如果MyObject定义一个operator<<).这就是重点std::stringstream:将"任何东西"重定向到字符串变得容易.
可以重定向到任何对象std::ostream(std::fstream,std::cout...)也被重定向到一个std:::stringstream(因为它派生自std::ostream太).然后你只需要声明一个std::ostream重定向operator(operator<<),它可以用来将对象重定向到处(文件,控制台,还有字符串......).
整点是,你可以声明operator+,并operator+=使其能够在您的对象串连到std::string.不过,如果你还希望将其重定向到一个流(文件,COUT),你就必须申报3个操作员(operator+,operator+=最后operator<<的流),都在做几乎同样的事情.最后,感谢std::stringstream,只有一个operator(operator<<)足以重定向到file,cout和string.
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |