简体   繁体   中英

Scanf does not detect enter when reading hex unsigned char values

I am trying to read a sequence of no more than 16 bytes in hex. I have to store that data in the following element to keep my code working:

//[...]
unsigned char *currentBlockState[10];
for(int i = 0; i < 10; i++) {
    currentBlockState[i] = new unsigned char[16];
}
//[...]

I want to store the information in the first element of the array. When I read 16 bytes, I use the following code:

for(int i = 0; i < 16; ++i){
    scanf("%02hhx",&currentBlockState[0][i]);
    //[...]
}

However, when I try to store less than 16 bytes and fill the remaining elements with 0, the program does not detect the enter key an keeps waiting for an hex value. I have also tried the following scanf modes:

scanf("%02hhx[^\n]",&currentBlockState[0][i]);
int x = scanf("%02hhx[^\n]%*c",&currentBlockState[0][i]);

What can I do to solve this?

Edit: I am using scanf because it is the easiest way I know to read hex values as a byte (unsigned char) array, of 128 bits length. I need it that way for a cryptographic problem I am trying to solve.

Thanks to everyone who commented, I did a code to read input as text and then parsed it as some of you said. This may not be the best option, but it worked for me:

std::cout << "Hex text input (without spaces):";
std::string tmp = "", hextxt = "";
std::cin >> hextxt;
        
for(int j = 0; j < hextxt.length(); j+=2) {
    tmp.push_back(hextxt[j]);
    tmp.push_back(hextxt[j+1]);
    aux.push_back(tmp);
    tmp = "";
}
unsigned int c;
for(int j = 0; j < aux.size(); j++) {
    std::istringstream hexstr(aux[j]);
    hexstr >> std::hex >> c;
    bytes.push_back(c);
}
while(bytes.size() < 16) {
    std::istringstream hexstr("00");
    hexstr >> std::hex >> c;
    bytes.push_back(c);
}
for(int j = 0; j < bytes.size(); j++) {
    blocks[0][j] = bytes[j];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM