更多的背景,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 –