jeudi 23 avril 2020

C++11: How to parse a hex string from stringstream when leading character is alpha (abcdef)

I am attempting to read a hex value from a std::stringstream based on the example at https://en.cppreference.com/w/cpp/io/manip/hex. Everything works fine when the leading character of the string is a numeric character [0-9], but when the leading character is an alpha character [a-f,A-F] getting the value from the stream consumes the characters but doesn't assign a value to the integer. Is there a flag or something that needs to be set to tell stringstream or std::hex that this is, in fact, a valid hex value and should be interpreted as such?

I will probably just end up reading from the stream into a string and using std::stoi, but wondered why parsing directly from the stringstream doesn't work or if there is a way to make it work.

Example code:

#include <iostream>
#include <sstream>
#include <string>
int main()
{
    int anint = 0;
    std::stringstream ss;
    ss.str("1234abcd");
    ss >> std::hex >> anint;
    printf("anint = %x\n", anint);

    anint = 0;
    ss.str("a234abcd");
    ss >> std::hex >> anint;
    printf("anint = %x\n", anint);

    return 0;
}

Outputs:

anint = 1234abcd
anint = 0

Aucun commentaire:

Enregistrer un commentaire