c++ - 使用 Stringstream 将字符串转换为 Int

标签 c++ string casting int transformation

这里有个小问题:

int IntegerTransformer::transformFrom(std::string string){
    stream->clear();
    std::cout<<string<<std::endl;;
    (*stream)<<string;
    int i;
    (*stream)>>i;
    std::cout<<i<<std::endl;
    return i;
}

我用字符串“67”调用这个函数(其他值也不起作用)我得到这个输出:

67
6767

最佳答案

您是否注意到函数本身有两个 std::cout

除此之外还要添加:

stream->str(""); //This ensures that the stream is empty before you use it.
(*stream)<<string;

顺便问一下,你为什么不使用 boost::lexical_cast

int IntegerTransformer::transformFrom(std::string s){
     return boost::lexical_cast<int>(s);
}

关于c++ - 使用 Stringstream 将字符串转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6939260/

相关文章:

Python正则表达式根据数字后面的逗号进行分割

python - 如何获取每个字符串变体以及每个位置的可能性列表

c# - 指定的转换在 linq 查询中无效

c++ - 了解 Qt View 模型架构 : when to create and how to cleanup indexes in QAbstractItemModel implementation?

c++ - 具有特征库的 MatrixFree-Matrix(和 Vector)乘积

python - Objective-C 字符串操作

Java 数组窄转换规则

c# - 我应该转换我的 lambda 还是转换 IEnumerable?

c++ - 使用 boost.python 将通用 C++ 库绑定(bind)到 python

c++创建具有数组作为成员的对象