什么是“字符串”、“流”? 和“stringstream” C++ 中的类?

发布于 2024-07-09 11:03:36 字数 50 浏览 5 评论 0原文

我想知道c++中string和stream有什么区别,stringstream是什么?

I want to know what's the difference between string and stream in c++, and what's stringstream?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

世界和平 2024-07-16 11:03:36

非常非正式地:字符串是字符的集合,流是操纵移动数据的工具。 字符串流是一个 C++ 类,可让您使用字符串作为流的数据源和目标。

Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.

恍梦境° 2024-07-16 11:03:36
  • istreamostream:流数据接口(文件、套接字等)
  • istringstream:包装字符串并提供其内容的 istream
  • ostringstream:保存写入内容的 ostream它作为字符串

示例:

istringstream datastream("1 2 3");

int val;
datastream >> val;
cout << val << endl; // prints 1

datastream >> val;
cout << val << endl; // prints 2

datastream >> val;
cout << val << endl; // prints 3


ostringstream outstream;
outstream << 1 << "+" << 2 << "=" << 3;
cout << outstream.str() << endl; // prints "1+2=3"
  • istream and ostream: interfaces to streaming data (files, sockets, etc.)
  • istringstream: an istream that wraps a string and offers its contents
  • ostringstream: an ostream that saves the content written to it as a string

Example:

istringstream datastream("1 2 3");

int val;
datastream >> val;
cout << val << endl; // prints 1

datastream >> val;
cout << val << endl; // prints 2

datastream >> val;
cout << val << endl; // prints 3


ostringstream outstream;
outstream << 1 << "+" << 2 << "=" << 3;
cout << outstream.str() << endl; // prints "1+2=3"
铜锣湾横着走 2024-07-16 11:03:36

我的猜测是,字符串流就像 iostream,但不是写入或读取文件,而是写入或读取字符串。

My guess is that a stringstream is like an iostream, but instead of writing to or reading from a file, you write to or read from a string.

天煞孤星 2024-07-16 11:03:36

在 C 和/或 Unix 中,基本的隐喻是文件。 标准输出、标准输入、网络套接字均使用文件描述符表示。 因此,您可以使用 fprintf() 写入这些“文件”,而无需了解底层的实际内容。

作为一种更安全、更酷的替代方案,C++ 提出了 iostream 作为几乎内置于其中的基本隐喻使用 << 运算符的语言。 同样,文件、字符串和(带有库)网络可以使用流进行访问,而无需知道它们是什么。

In C and/or Unix, the basic metaphor was the file. Standard out, standard in, network sockets were all represented using file descriptors. Thus you can use fprintf() to write into these "files" without knowing what's really underneath.

As a safer and cooler alternative, C++ presented iostream as the basic metaphor which is almost built into the language using << operator. Again, files, strings and (with library) network can be accessed using streams without knowing what it is.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文