Getting a byte value using stringstream

I have this (incorrect) sample code to get a value from a string stream and store it in a variable byte size (it should be in one byte of var, not in 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 way out when I run this is 49, which is not what I would like to see. Obviously, this is considered a char, not a simple numeric value. What is the most C ++ ish way to force c to hold 1, not 49 when casting to int?

Thanks!

+6
c ++ iostream stringstream
source share
5 answers

The C ++ method itself - ish, of course, parses the value correctly by reading it in another integral type, and then translates to the byte type (since reading in 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); 

Ive used unsigned int since this is most natural, although unsigned short will of course also work.

+10
source share

A char will always do this. You need to read int (or float or double, etc.), otherwise the wrong "formatter" will be called.

 unsigned char c; unsigned int i; ss >> i; c = i; 
+3
source share

Cross out '0' from it:

 cout << (int) (c - '0') << endl; 

'0' has a value of 48, so 49 - 48 = 1

+2
source share
 stringstream ss( "1" ); unsigned char c; { unsigned int i; ss >> i; c = i; } cout << static_cast<int>(c) << endl; 

Will work. You could also do some unsafe pointer things, but I would just go with the above.

0
source share

This is because string constants in C ++ are treated as text.
Two options:

  • String encoding using escaped numbers:

    • Octal numbers: \ 0 <d> {1,3}
    • Hex Numbers: \ 0x <d> {2}

    std :: stringstream ("\ 01 \ 02 \ 03 \ 04 \ 0xFF");

  • Or create a char array and initialize it with numbers:

    char data [] = {0, 1, 2,3, 4, 255};

What about:

 #include <iostream> #include <sstream> using namespace std; int main(int argc, char** argv) { char x[] = {1,0}; stringstream ss( x); unsigned char c; ss >> c; cout << (int) c << endl; } 
-one
source share

All Articles