字符串流在C++编程中的作用是什么
What is the function of stringstream in C++ programmng?
请允许我是编程新手。我刚开始使用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"提供了大量功能,否则很难编程)。
相关文章:
- "using namespace std;"在C++的作用是什么?
- 此代码中的" "是什么,它的基本作用是什么?
- 在模板参数中使用 {} 在 type_trait{} 中时,其作用是什么<T>?
- <<、>>算子在循环中的作用是什么
- 在c++中,减号和加号对字符串的作用是什么
- 窄集(_cast)的作用是什么
- 在这种情况下,#define 的作用是什么?
- 遍历模板参数包,没有争论的专业化的作用是什么?
- 在 c++ 中,没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?
- 访问多个阵列时 CPU 缓存的作用是什么?
- 以下表达式的作用是什么:x = (a1,a2,..,n);
- 私人成员的作用是什么?
- 这段代码的作用是什么?
- *.exp文件的作用是什么
- ifstream::open()真正的作用是什么
- 如何在矩阵中使用指针.这行代码的作用是什么:int r=**(++b);
- 这个函数的作用是什么?与夹紧值有关
- 这个运算符()语法的作用是什么
- std::函数的模板参数中“const”修饰符和引用的作用是什么
- 字符串流在C++编程中的作用是什么