The C++ std::istream::read() function is used to read a specified number of characters from an input stream into a buffer. It is commonly employed for binary input operations. This function takes two arguments: a pointer to the buffer where data will be stored and the number of characters to read.
SyntaxFollowing is the syntax for std::istream::read() function.
istream& read (char* s, streamsize n);Parameters
This function returns the basic_istream object (*this).
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies the elements in the array pointed by s and the stream object.
ExampleIn the following example, where we are going to consider the basic usage of read() function.
#include <iostream> #include <sstream> int main() { std::istringstream a("Hi, Namaste"); char b[6]; a.read(b, 2); b[2] = '\0'; std::cout << "Result : " << b << std::endl; return 0; }Output
Following is the output of the above code −
Result : HiExample
Consider the following example, where we are going to read the 4-byte integer from the integer stream.
#include <iostream> #include <sstream> int main() { std::istringstream x("\x11\x10\x00\01"); int a; x.read(reinterpret_cast<char*>(&a), sizeof(a)); std::cout << "Result : " << a << std::endl; return 0; }Output
If we run the above code it will generate the following output −
Result : 4113
istream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4