2011-11-28 62 views
6

例如字符串,如果我有这个小功能:如何返回包含字符串/ int变量会生成

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+’

我在做什么错?我几乎从类中复制了一个例子,并将其改为适合我的功能。

回答

10

您试图将整数连接到字符串,并且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"); 
} 
+0

工作得很好,谢谢。 – Rima

+0

虽然你的第一句话是正确的,但由于OP没有连接'std :: string's,所以这个问题也完全不相关。 –

+0

@MarkB你说得对。希望更新的答案更清楚。 –

1

您不能将字符串文字(如“hello”)添加到整数。这是编译器对你说的。这是你的问题的部分答案。请参阅如何在另一篇文章中完成您想要的内容。

+0

事实上,您*可以*将char和char *都添加到整数。只是大部分时间根本不会做你想要的。 –

+0

@MarkB我会改进我的答案。 – Beginner

2
#include <sstream> 

string lw(int a, int b) {  
    std::string s; 
    std::stringstream out; 
    out << "lw $" << a << "0($" << b << ")" << endl; 
    s = out.str(); 
    return s; 
} 
+0

工程,但你支付了out.str()''多余的本地副本......为什么要做这个副本? (另外我会指出一些我直到最近才学到的东西,那就是在一般情况下'endl'不是''\ n“'的同义词 - 它刷新流,所以我停止了“整理”使用'“\ n”'使用'endl' ...) – HostileFork

2

使用ostringstream:

#include <sstream> 
... 
string lw(int a, int b) { 
    std::ostringstream o; 
    o << "lw $" << a << "0($" << b << ")\n"; 
    return o.str(); 
} 
0

要理解这个问题,你要知道,在C++中,字符串文字像"lw $"作为const char[]视为从C语言继承。然而,这意味着你只能得到为数组定义的运算符,或者在这种情况下是数组降级到指针的情况。

所以会发生什么是你有一个字符串文字,然后添加一个整数,创建一个新的指针。然后,您尝试添加另一个字符串文字,该文字再次降级为char*。您不能将两个指针相加,然后生成您所看到的错误。

您试图将整数格式化为带有一些分隔文本的字符串格式。在C++中,这样做的规范方式是使用字符串流:

#include <sstream> 

string lw(int a, int b) 
{ 
    std::ostringstream os; 
    os << "lw $" << a << "0($" << b << ")\n"; 
    return os.str(); 
} 
相关问题