hexadecimal value in input string needs to be checked
I am basically trying to get a user to input a hexadecimal input via getline into a string as i will do other operations on this. (using c++ .net stuff won't work)
i do not want to break this into chars per say and then go through each char in the string and see if its in range from [0-9] or [Aa-Ff].
Instead, I wanted to know if there was a cool function that anyone knew of or a better way to do it. I am aware of the strtoul function but it returns a long. this will force me to then i guess pass it to a stream to make it back into a string again.
another thing with the long i am not sure of if i have to worry about 64 bit long vs 32 bit long. I am developing this on a linx box using an intel processor but it could be used on a unix box whose processor could be 64 bit i am not sure.
so i guess there are two questions here really. any help would be most welcome
could I get an answer on: can you also comment on my second question about the long? even though i don't have to worry about that now...if i save a variable in a long using a 32 bit system....would that change ( i imagine so the size of long should change on a 64开发者_开发技巧 bit processor) what would this mean for the info saved in the variable? and second in order to avoid the whole little/big endian thing i saved it in a long thinking since its a register of sorts it would not be an issue with porting. was i wrong to think that?
thanks
Checking each char is the only way it can be done, period.
However, you may be interested in isxdigit(int character) which returns 0 if the character passed isn't a valid hexadecimal character (note that x is not included as a valid character).
You can test if it's a hex string in a single line using algorithms, though it's a bit ugly. If you're using Boost, you can pretty it up a lot by using boost::bind.
The headers required by this snippet are <locale>, <functional>, and <algorithm>.
bool is_hex_string(std::string& str) {
return std::count_if(str.begin(), str.end(),
std::not1(std::ptr_fun((int(*)(int))std::isxdigit))) > 0;
}
if (sscanf(string, "%x", &val) != 1) // handle your error here
int val;
scanf("%x", &val);
? (Won't check if the whole line is valid.)
精彩评论