更多的背景,see here读取二进制数据`stringstream`
我使用的是stringstream
通过二进制数据读取。到目前为止,我只是写一个虚拟程序来让课堂感到舒适。这是我的计划:
#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;
}
}
输出:
he ==> 68 65
ll ==> 6C 6C
o ==> 6F 20
th ==> 74 68
e ==> 65 00
==> 00 00
我对此有2个问题:
- 为什么,当我执行
ss.get()
,我要输入3,而比2,一次读取流2个字符? - 它为什么终止于第一个空字符,我如何防止这种情况发生?
相关http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –