Read binary data from std::cin

Allan picture Allan · Sep 28, 2011 · Viewed 19k times · Source

What is the easiest way to read binary (non-formated) data from std::cin into either a string or a stringstream?

Answer

Lou Franco picture Lou Franco · Sep 28, 2011

std::cin is not opened with ios_binary. If you must use cin, then you need to reopen it, which isn't part of the standard.

Some ideas here: http://compgroups.net/comp.unix.programmer/How-can-I-reopen-std-cin-and-std-cout-in-binary-mode.

Once it's binary, you can use cin.read() to read bytes. If you know that in your system, there is no difference between text and binary (and you don't need to be portable), then you can just use read without worrying.