OK ASCII デコードを扱うことはまったく悪い考えであり、実際には質問に答えていないと思います。
orを読んだときにのみsetw()
orが機能するため、コードが機能しないと思います。推しはここからistream::width()
std::string
char*
標準の C++ iostream コンバーターの長所をどれだけ活用できるか。stringstream
クラスstring
をバッファとして使用するアイデアを思いつきました。n
問題は、文字をバッファに読み込みstringstream
、コンバータ機能として使用することです。
これが最適なバージョンかどうかはわかりません。おそらくそうではありません。
コード:
#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';
}
結果:
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
ご覧のとおり、エラー耐性はあまり高くありません。それにもかかわらず、特定の条件で機能し、ループに展開でき、最も重要なのはiostream
変換機能を使用するため、ASCII マジックはありません。ただし、C/ASCII の方がおそらく高速です。
PS。改良版。単純なchar[2]
バッファーを使用し、フォーマットされていない書き込み/読み取りを使用して、バッファーを介してデータを移動します ( get
/write
ではなくoperator<<
/ operator>>
)。その理由は非常に単純です。2 バイトのデータを移動するために特別なことは必要ありません。ただし、フォーマットされたエクストラクタを使用して変換を行います。便宜上、ループ版にしました。しかし、それは非常に単純ではありませんでした。非常に重要な行を理解するのに40分かかりました。それらがないと、抽出は最初の 2 文字に対して機能します。
#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;
}
出力例:
luk32@genaker:~/projects/tmp$ ./a.out
read vals: 0aabffc
(0a) 0a 10
(ab) ab 171
(ff) ff 255
c
意図したとおりに読まれていないことに注意してください。
ここで必要なものがすべて見つかりましたhttp://www.cplusplus.com/reference/iostream/