c++ - 如何返回包含字符串/整数变量的字符串

标签 c++ string

例如,如果我有这个小功能:

string lw(int a, int b) {    
    return "lw $" + a + "0($" + b + ")\n";
}

....并在我的主函数中调用 lw(1,2) 我希望它返回 "lw $1, 0($2)"

但我不断收到错误消息:invalid operands of types ‘const char*’ and ‘const char [11]’ to binary ‘operator+’

我做错了什么?我几乎从类里面复制了一个示例,并对其进行了更改以适合我的功能。

最佳答案

您正在尝试将整数连接到字符串,而 C++ 无法转换此类不同类型的值。你最好的选择是使用 std::ostringstream构建结果字符串:

#include <sstream>

// ...

string lw(int a, int b)
{
    ostringstream os;
    os << "lw $" << a << "0($" << b << ")\n";
    return os.str();
}

如果你有Boost , 你可以使用 Boost.Lexical_cast :

#include <boost/lexical_cast.hpp>

// ...

string lw(int a, int b)
{
    return
        string("lw $") +
        boost::lexical_cast<std::string>(a) +
        string("0($") +
        boost::lexical_cast<std::string>(b) +
        string(")\n");
}

现在 C++11 及更高版本有 std::to_string :

string lw(int a, int b)
{
    return
        string("lw $") +
        std::to_string(a) +
        string("0($") +
        std::to_string(b) +
        string(")\n");
}

关于c++ - 如何返回包含字符串/整数变量的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8297070/

相关文章:

c++ - 使用 pThreads 在线程之间共享 3D 数组

python - 均匀地并排打印 2 个均匀填充的列表

c++ - 模板和标题问题

c++ - DLL 比静态链接慢吗?

c++ - 在模板中使用 operator<

c++ - CListCtrl ListView 中的垂直滚动条

java - 如何找到文本中复合词的出现

python - 如何准备一个包含整数、 float 和字符串的列表?

string - slice 后释放字符串以进行垃圾回收的正确方法

MYSQL 更新字符串的一部分(如果该部分不在字符串中),如果存在则不执行任何操作