istringstream到int8_t产生意外的结果 [英] istringstream to int8_t produce unexpected result

查看:352
本文介绍了istringstream到int8_t产生意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读此常见问题,我选择使用istringstream将我的输入字符串转换为数值。

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;
}

当T是int,short,long或float时,值。
但是当T是int8_t时,这个代码不工作。

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.

例如,如果我的输入字符串是10,getValue返回一个int8_t值等于49。

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

在ASCII表中使用49 =='1',我想>>运算符只读取输入字符串中的第一个字符并停止。

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

推荐答案

执行输入流的工作方式如下:

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;

结果是'a',因为 char 输入流读取char的char。

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

要解决这个问题,请为您的模板方法提供一个专门的实现。并读入 int ,然后检查边界并将该值转换为 int8_t

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.

这篇关于istringstream到int8_t产生意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆