I’m manipulating raw input of keyboard in std c++.
The code working with libstdc++ but libc++.
When UP arrow key stroked,
- get
1b 5b 41output if compiled withclang++ -std=c++23 -stdlib=libstdc++ rawkey.cpp. This is correct. - get
1boutput if compiled withclang++ -std=c++23 -stdlib=libc++ rawkey.cpp
This issue can be reproduced in three deives:
- HP Z2 G9, i9-13900K, Ubuntu 24.10, clang v19
- NVidia P3710 Developer Kit, Ubuntu 20.04(DOS 6.0.10), clang v18
- Arbor FPC-780X, i7-4785T, Fedora 41, clang v19
Here is the source code to re-produce:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
using namespace std;
void get_raw_key()
{
auto buf = cin.rdbuf();
vector<int> keys;
string endline("\r\n");
auto pump_buf = [&]() {
cerr << ""; // cin.sync();
// without this line, debug() has no output
// if compiled with libstdc++, but libc++ works
// while libc++ can fetch only one unformatted char
keys.clear();
keys.push_back(buf->sbumpc()); // buf->sgetc() buf->sbumpc() getchar() cin.get()
while (buf->in_avail() > 0)
keys.push_back(buf->sbumpc());
};
auto dump_key = [&]() {
stringstream sstr;
for (const auto num : keys)
sstr << hex << setw(2) << setfill('0') << num << ' ';
auto str = sstr.str();
if (str.size() > 0)
str.erase(str.end() - 1);
return str;
};
auto debug = [&]() {
static int count = 0;
cout << endline << __func__
<< "(" << count << ")"
<< ", in_avail: " << buf->in_avail()
<< ", gcount: " << cin.gcount()
// << ", bad: " << cin.bad()
// << ", eof: " << cin.eof()
// << ", fail: " << cin.fail()
// << ", good: " << cin.good()
<< ", keys[" << keys.size()
<< "]: " << dump_key()
<< endline;
count++;
};
debug();
pump_buf();
dump_key();
debug();
}
int main(int argc, char *argv[])
{
system("stty raw");
cin.sync_with_stdio(false);
cout << "Please stroke UP arrow key\r\n";
get_raw_key();
cout << "\r\n";
return 0;
}