I've got this (incorrect) sample code for getting a value out of stringstream and storing it in a byte-sized variable (it needs to be in a single byte var, not an int):
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv)
{
stringstream ss( "1" );
unsigned char c;
ss >> c;
cout << (int) c << endl;
}
The output when I run this is 49, which is not what I would like to see. Obviously, this is being treated as a char and not simple numeric value. What is the most c++ish way to get c to hold a 1 rather than a 49 when casted to an int?
Thanks!
The most C++-ish way is certainly to parse the value properly by reading into another integral type, and then cast to a byte type (since reading into a char
will never parse – it will always just read the next character):
typedef unsigned char byte_t;
unsigned int value;
ss >> value;
if (value > numeric_limits<byte_t>::max()) {
// Error …
}
byte_t b = static_cast<byte_t>(value);
I’ve used unsigned int
since that’s the most natural, although unsigned short
would of course also work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With