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?
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.)
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:
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