OK I think dealing with ASCII decoding is a bad idea at all and does not really answer the question.
I think your code does not work because setw()
or istream::width()
works only when you read to std::string
or char*
. I guess it from here
How ever you can use the goodness of standard c++ iostream converters. I came up with idea that uses stringstream
class and string
as buffer. The thing is to read n
chars into buffer and then use stringstream
as a converter facility.
I am not sure if this is the most optimal version. Probably not.
Code:
#include <iostream>
#include <sstream>
int main(void){
int c;
std::string buff;
std::stringstream ss_buff;
std::cin.width(2);
std::cin >> buff;
ss_buff << buff;
ss_buff >> std::hex >> c;
std::cout << "read val: " << c << '\n';
}
Result:
luk32@genaker:~/projects/tmp$ ./a.out
0a10
read val: 10
luk32@genaker:~/projects/tmp$ ./a.out
10a2
read val: 16
luk32@genaker:~/projects/tmp$ ./a.out
bv00
read val: 11
luk32@genaker:~/projects/tmp$ ./a.out
bc01
read val: 188
luk32@genaker:~/projects/tmp$ ./a.out
01bc
read val: 1
And as you can see not very error resistant. Nonetheless, works for the given conditions, can be expanded into a loop and most importantly uses the iostream
converting facilities so no ASCII magic from your side. C/ASCII would probably be way faster though.
PS. Improved version. Uses simple char[2]
buffer and uses non-formatted write/read to move data thorough the buffer (get
/write
as opposed to operator<<
/operator>>
). The rationale is pretty simple. We do not need any fanciness to move 2 bytes of data. We ,however, use formatted extractor to make the conversion. I made it a loop version for the convenience. It was not super simple though. It took me good 40 minutes of fooling around to figure out very important lines. With out them the extraction works for 1st 2 characters.
#include <iostream>
#include <sstream>
int main(void){
int c;
char* buff = new char[3];
std::stringstream ss_buff;
std::cout << "read vals: ";
std::string tmp;
while( std::cin.get(buff, 3).gcount() == 2 ){
std::cout << '(' << buff << ") ";
ss_buff.seekp(0); //VERY important lines
ss_buff.seekg(0); //VERY important lines
ss_buff.write(buff, 2);
if( ss_buff.fail() ){ std::cout << "error\n"; break;}
std::cout << ss_buff.str() << ' ';
ss_buff >> std::hex >> c;
std::cout << c << '\n';
}
std::cout << '\n';
delete [] buff;
}
Sample output:
luk32@genaker:~/projects/tmp$ ./a.out
read vals: 0aabffc
(0a) 0a 10
(ab) ab 171
(ff) ff 255
Please note, the c
was not read as intended.
I found everything needed here http://www.cplusplus.com/reference/iostream/