Jonathan Mee
Jonathan Mee

Reputation: 38919

Streaming in a char Number

Is there a way to stream in a number to a unsigned char?

istringstream bytes( "13 14 15 16 17 18 19 20" );
unsigned char myChars[8];

for( int i = 0; i < 8 && !bytes.eof(); i++ )
{
    bytes >> myChars[i];
    cout << unsigned( myChars[i] ) << endl;
}

This code currently outputs the ascii values of the first 8 non-space characters:

49 51 49 52 49 53 49 54

But what I want is the numerical values of each token:

13 14 15 16 17 18 19 20

Upvotes: 1

Views: 134

Answers (2)

Jonathan Mee
Jonathan Mee

Reputation: 38919

So there is a lot of error checking that you'll bypass to do this without a temporary. For example, does each number being assigned fit in a byte and are there more numbers in bytes than elements of myChars? But presuming you've already delt with those you can just use an istream_iterator<unsigned short>:

copy(istream_iterator<unsigned short>{ bytes }, istream_iterator<unsigned short>{}, begin(myChars))

Live Example


An additional note here: A char[] typically contains a null terminated string. Presuming that's not what you intend, it would be gracious of you to indicate to the reader that's not how you're using it. In you were given int8_t/uint8_t to do just that. Using something like: uint8_t myChars[8] would make your code more readable.

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129374

You are reading a char at a time, which means you get '1', '3', skips the space, '1', '4', skips the space, etc.

To read the values as NUMBERS, you need to use an integer type as a temporary:

unsigned short s;
bytes >> s;
myChars[i] = s; 

Now, the stream will read an integer value, e.g. 13, 14, and store it in s. Then you convert it to a unsigned char with myChars[i] = s;.

Upvotes: 1

Related Questions