【问题标题】:Adding a double to the end of a string (C++)在字符串末尾添加双精度 (C++)
【发布时间】:2012-07-22 02:18:00
【问题描述】:

所以,基本上这就是我的代码中出现问题的地方。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>

void main()
{
    double k = 10.0;
    string out;
    out = "V";
    out += ".";
    out << k;   <---
}

我尝试编译,但出现此错误:

错误 C2784: 'std::basic_ostream<_elem> &std::operator &&,_Ty)' : 无法推导出 'std::basic_ostream &&' from 'std::string'

...指向带箭头的线。我做错了什么?

【问题讨论】:

标签: c++ string operator-overloading double


【解决方案1】:

使用std::stringstreamboost::lexical_cast

out += boost::lexical_cast<std::string>(k);

std::to_string,如果你可以使用 C++11

【讨论】:

  • 嗯,这似乎是在我的情况下对我最有用的一个......谢谢!虽然我对boost库比较陌生。
【解决方案2】:

尝试以下方法:-

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

【讨论】:

    【解决方案3】:

    您正在尝试使用string 而不是stringstream。没有定义将 string 作为其第一个参数的运算符 &lt;&lt;,这是编译器试图告诉您的(以一种相当神秘的方式)。

    stringstream out;
    out << "V." << k;
    string s = out.str();
    

    如果你使用 C++11,你可以这样写:

    double k = 10.0;
    string out;
    out = "V";
    out += ".";
    out += to_string(k);
    

    【讨论】:

    • 那么我应该使用什么运算符而不是
    • @ked 为什么不使用stringstream?它只是一个 string 对象的包装器。
    • @ked 如果你使用 C++11,你可以使用out += to_string(k)。在 C++11 之前,stringstream 是您的最佳选择。
    • 好的,我想我别无选择,只能使用它......但现在我收到一个编译器错误,说它是一个未定义的类。
    • @ked 那你为什么不能把你的替身直接写给fstream呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多