-2

After read this FAQ, i choose to use istringstream to convert my input string to numerical value.

My code is look like this:

<template T>
T Operand<T>::getValue(const std::string &s)
{
    T _value;
    std::istringstream v_ss(s);

    v_ss >> _value;
    return _value;
}

When T is int, short, long or float, no problem i get correct value. But when T is int8_t, this code doesn't work.

By exemple, if my input string is "10", getValue return me a int8_t with value equals 49.

With 49 == '1' in ASCII table, i guess the >> operator just read the first char in input string and stop.

Is there a trick or something i don't understand in the FAQ ?

Community
  • 1
  • 1
PanzerKadaver
  • 363
  • 3
  • 12
  • 1
    You should post some small, compilable test case instead of some code full of errors. But it looks like `int8_t` is treated as a `char` type. – juanchopanza Mar 02 '14 at 12:36
  • 1
    Iostreams have special overloads for character types. Alas. On the bright side, that means that `cout << '1'` prints a `1` and not `49`. – Kerrek SB Mar 02 '14 at 12:37
  • @juanchopanza : sry for the little return mistake – PanzerKadaver Mar 02 '14 at 12:44
  • 3
    That's not the only one :-) But even without syntax errors, this is not self-contained. [This is what a test-case looks like](http://ideone.com/fdC1oc). – juanchopanza Mar 02 '14 at 12:45

1 Answers1

2

The problem is int8_t is implemented as char.

The implementation of the input stream is working like this:

char x;
std::string inputString = "abc";
std::istringstream is(inputString);

is >> x;
std::cout << x;

The result is 'a', because for char the input stream is read char for char.

To solve the problem, provide a specialised implementation for your template method. and reading into a int, then check the bounds and convert the value into a int8_t.

Flovdis
  • 2,945
  • 26
  • 49