How to write custom input stream in C++

The proper way to create a new stream in C++ is to derive from std::streambuf and to override the underflow() operation for reading and the overflow() and sync() operations for writing. For your purpose you’d create a filtering stream buffer which takes another stream buffer (and possibly a stream from which the stream buffer can … Read more

Are there binary memory streams in C++

To read and write binary data to streams, including stringstreams, use the read() and write() member functions. So unsigned char a(1), b(2), c(3), d(4); std::stringstream s; s.write(reinterpret_cast<const char*>(&a), sizeof(unsigned char)); s.write(reinterpret_cast<const char*>(&b), sizeof(unsigned char)); s.write(reinterpret_cast<const char*>(&c), sizeof(unsigned char)); s.write(reinterpret_cast<const char*>(&d), sizeof(unsigned char)); s.read(reinterpret_cast<char*>(&v), sizeof(unsigned int)); std::cout << std::hex << v << “\n”; This gives 0x4030201 … Read more

How can I print 0x0a instead of 0xa using cout?

This works for me in GCC: #include <iostream> #include <iomanip> using namespace std; int main() { cout << “0x” << setfill(‘0′) << setw(2) << right << hex << 10 << endl; } If you are getting sick and tired of iostream’s formatting quirkiness, give Boost.Format a try. It allows good-old-fashioned, printf-style format specifiers, yet it … Read more

Converting ostream into standard string

The question was on ostream to string, not ostringstream to string. For those interested in having the actual question answered (specific to ostream), try this: void someFunc(std::ostream out) { std::stringstream ss; ss << out.rdbuf(); std::string myString = ss.str(); }

Output unicode strings in Windows console app

I have verified a solution here using Visual Studio 2010. Via this MSDN article and MSDN blog post. The trick is an obscure call to _setmode(…, _O_U16TEXT). Solution: #include <iostream> #include <io.h> #include <fcntl.h> int wmain(int argc, wchar_t* argv[]) { _setmode(_fileno(stdout), _O_U16TEXT); std::wcout << L”Testing unicode — English — Ελληνικά — Español.” << std::endl; } … Read more