Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a byte value using stringstream

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!

like image 812
twk Avatar asked Jul 28 '10 19:07

twk


1 Answers

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.

like image 194
Konrad Rudolph Avatar answered Sep 22 '22 12:09

Konrad Rudolph