字符串流在C++编程中的作用是什么

What is the function of stringstream in C++ programmng?

本文关键字:作用 是什么 编程 C++ 字符串      更新时间:2023-10-16

请允许我是编程新手。我刚开始使用c++,到了使用字符串流的地步。这些东西让我有点困惑。请有人帮我。

对于您的问题,您知道如何使用std::cout来编写输出吗?你知道如何使用std::cin来读取输入吗?然后,您就知道了使用任何流所需的一切,包括std::stringstream(及其仅输出和仅输入的同级)。

不同之处在于,字符串流将写入(或读取)字符串,而不是控制台或终端。

例如,假设你想从一些其他文本和一些数字中构造一个字符串,那么你可以使用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"

输入字符串流可能不像输出字符串流那样经常使用,但可以用于逐行解析文件中的输入,方法是将输入文件流中的一行读取到std::string中,然后使用输入字符串流提取数据,就像使用std::cin一样。

除了Joachim Pileborg的解释之外,我想添加一些

字符串流是内部的typedef "basic_stringstream<char>"

typedef basic_stringstream<char> stringstream;

流类对字符串进行操作。

此类的对象使用包含一系列字符的字符串缓冲区。这个字符序列可以作为字符串对象直接访问,使用成员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"提供了大量功能,否则很难编程)。