Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

c++ - istringstream to int8_t produce unexpected result

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...