for more background, see here
I am using a stringstream
to read through binary data. As of now, I am simply writing a dummy program to get comfortable with the class. Here's my program:
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
string bytes2hex(char* bytes, int n){
stringstream out;
for (int i = 0;i < n;i++){
out << setfill ('0') << setw(2) << hex << (int) bytes[i] << " ";
}
string st = out.str();
for(short k = 0; k < st.length(); k++)
{
st[k] = toupper(st[k]);
}
return st;
}
int main(){
stringstream ss;
ss << "hello the\0re my\0\0\0 friend";
while (ss.peek() != EOF){
char buf [2];
ss.get(buf, 3);
cout << buf << "\t==>\t" << bytes2hex(buf, 2) << endl;
}
}
Output:
he ==> 68 65
ll ==> 6C 6C
o ==> 6F 20
th ==> 74 68
e ==> 65 00
==> 00 00
I have 2 questions on this:
- Why is it that, when I execute
ss.get()
, I have to input 3, rather than 2, to read the stream 2 characters at a time? - Why does it terminate on the first null character, and how do I prevent that from happening?