Question

I have following code

unsigned char input;
vector <unsigned char> buffer;
while (cin >>input){
    buffer.push_back(input);
}

for (int i=0;i<buffer.size();i++)
    cout<<std::hex<<(int)buffer.at(i)<<endl;

and I call the program with binary file

./program <<binary_file

which consits of: (view from hex editor)

0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f

However I get the following output:

0
1
2
3
4
5
6
7
8
e
f
10
11
12
13
14
15
16
17
18
19
1a
1b
1c
1d
1e
1f

As you can see, the "9","a","b","c","d" is missing. Could you explain what's wrong? Am I missing something essential? thanks

Or could you suggest any other way how to load binary file from cin and store it in

vector<unsigned char> buffer
Was it helpful?

Solution

The characters 0x09 through 0x0D are whitespace, and as such are ignored by operator>> when extracting values. Use one of the std::cin.get() overloads if you want an unformatted character read (if you're programming on windows, carriage returns (0x0D) will still be ignored as part of a line end unless you reopen the standard input stream in binary mode).

You can also use the std::noskipws manipulator to disable leading whitespace skipping for formatted input functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top