Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

istringstream decimal integer input to 8-bit type

This:

#include <iostream>
#include <sstream>
#include <inttypes.h>

using namespace std;

int main (void) {
    istringstream iss("123 42");
    int8_t x;
    while (iss >> x) {
        cout << x << endl;
    }
    return 0;
}  

Produces:

1
2
3
4
2

But I want:

123
42

Casting iss >> (int)x (I initially tried this with a char) gives me "error: invalid operands to binary expression ('istringstream' (aka 'basic_istringstream') and 'int')" (clang) or "error: ambiguous overload for ‘operator>>’" (g++).

Is there a way to read the value as a number directly into an 8-bit type, or do I have to use an intermediary store?

like image 490
CodeClown42 Avatar asked Aug 10 '14 16:08

CodeClown42


2 Answers

There is no built-in 8-bit type; you're using an alias for signed char and IOStreams will always extract a single ASCII letter when you do formatted input into any kind of char.

So, yes, use an intermediary store, or wrap int8_t in a new class that provides its own overloads for formatted I/O (which I'd consider overkill unless you have strict memory and/or performance requirements).

(Your attempt of iss >> (int)x is very confused; conversions are used on expressions you're about to take the value of, not for lvalues naming objects that you want to set the value of.)

like image 125
Lightness Races in Orbit Avatar answered Nov 11 '22 06:11

Lightness Races in Orbit


You have to use an intermediate type or do the parsing yourself. All char-types (char, signed char and unsigned char) are treated as text elements, not integers. int8_t is probably just a typedef for one of them, which is why your code fails.

Note:

  • The output will suffer from the same issues.
  • Don't use C-style casts, they almost only cause errors.
  • Checking for EOF before an input operation is useless, you need to check for failure afterwards instead.
like image 2
Ulrich Eckhardt Avatar answered Nov 11 '22 07:11

Ulrich Eckhardt