C++ Library - <spanstream>
The <spanstream> header is used for the input and output operations within the C++ standard library. This header provides a way to manipulate the input and output streams using spans, which are contiguous sequences of elements.
The <spanstream> is used in scenarios where data is being read from or written to various formats. It provides a set of functions that allow for conversion, the commonly used C++ <spanstream> functions are listed below along with their description.
Including <spanstream> Header
To include the <spanstream> header in your C++ program, you can use the following syntax.
#include <spanstream>
Functions of <spanstream> Header
Below is list of all functions from <spanstream> header.
| Sr.No | Functions & Description |
|---|---|
| 1 | operator=
It move-assignments the spanstream. |
| 2 | swap
It swaps two spanstream objects. |
| 3 | rdbuf
It obtains the address of the wrapped raw span device object. |
| 4 | span
It gets or sets the underlying buffer of the wrapped span device object. |
| 5 | setbuf
It attempts to replace the controlled character sequence with an array. |
| 6 | seekoff
It repositions the next pointer in the input sequence, output sequence, or both, using relative addressing. |
| 7 | seekpos
It repositions the next pointer in the input sequence, output sequence, or both using absolute addressing. |
Inserting a Character
In the following example, we are going to use the put() to insert a single character into the stream.
#include <spanstream>
#include <iostream>
#include <span>
int main() {
char a[5];
std::ospanstream os(a);
os.put('X');
os.put('Y');
std::cout << "Result : " << a << std::endl;
return 0;
}
Output
Output of the above code is as follows −
Result : XY
Reading the Characters
Consider the following example, where we are going to use the read() to read the characters.
#include <spanstream>
#include <iostream>
#include <span>
int main() {
char a[] = "Welcome";
std::ispanstream is(a);
char x[8];
is.read(x, 3);
x[3] = '\0';
std::cout << "Result : " << x << std::endl;
return 0;
}
Output
Following is the output of the above code −
Result : Wel