C++ 如何返回包含string/int变量的字符串
例如,如果我有这个小功能:C++ 如何返回包含string/int变量的字符串,c++,string,C++,String,例如,如果我有这个小功能: string lw(int a, int b) { return "lw $" + a + "0($" + b + ")\n"; } …并在我的主函数中调用lw(1,2),我希望它返回“lw$1,0($2)” 但我一直收到一个错误:类型为“const char*”和“const char[11]”的无效操作数转换为二进制“operator+” 我做错了什么?我几乎是从类中复制了一个示例,并对其进行了修改以适应我的函数。不能将字符串文字(如“hello
string lw(int a, int b) {
return "lw $" + a + "0($" + b + ")\n";
}
…并在我的主函数中调用lw(1,2)
,我希望它返回“lw$1,0($2)”
但我一直收到一个错误:类型为“const char*”和“const char[11]”的无效操作数转换为二进制“operator+”
我做错了什么?我几乎是从类中复制了一个示例,并对其进行了修改以适应我的函数。不能将字符串文字(如“hello”)添加到整数中。这就是编译器对你们说的。这是对你问题的部分回答。请在其他帖子中查看如何实现您的目标。
\include
#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;
}
字符串lw(inta,intb){
std::字符串s;
std::stringout;
OUT 您试图将整数连接到字符串,而C++不能转换这些不同类型的值。您最好使用的是构造结果字符串:
#include <sstream>
// ...
string lw(int a, int b)
{
ostringstream os;
os << "lw $" << a << "0($" << b << ")\n";
return os.str();
}
使用ostringstream:
#include <sstream>
...
string lw(int a, int b) {
std::ostringstream o;
o << "lw $" << a << "0($" << b << ")\n";
return o.str();
}
#包括
...
字符串lw(整数a、整数b){
std::ostringstream o;
为了理解这个问题,你必须知道,在C++中,字符串代码(如<代码>)LW $“/Cube”被当作是从C语言继承的“代码> const char []/CODE。但是这意味着你只得到了为数组定义的运算符,或者在这种情况下,数组退化为指针的情况。
因此,发生的情况是,您有一个字符串文本,然后向其中添加一个整数,创建一个新指针。然后您尝试添加另一个字符串文本,该字符串文本再次降级为char*
。您不能将两个指针添加在一起,这将生成您看到的错误
您试图将整数格式化为具有一些分隔文本的字符串格式。在C++中,用String Fiels:
#include <sstream>
string lw(int a, int b)
{
std::ostringstream os;
os << "lw $" << a << "0($" << b << ")\n";
return os.str();
}
#包括
字符串lw(整数a、整数b)
{
std::ostringstream os;
操作系统可以工作,但你要为多余的out.str()
…本地副本付费。为什么要做那个副本?(我还要指出一些我直到最近才学到的东西,那就是在一般情况下endl
不是“\n”
”的同义词-它会刷新流。所以我停止了对“\n”的“整理”使用
使用endl
…)虽然你的第一句话是正确的,但它也与问题完全无关,因为OP没有连接std::string
s.@MarkB你是对的。更新了答案,希望能让它更清楚。事实上,你可以将char
和char*
添加到整数中。只是大部分时间根本不做什么“你不想,”马克B我会改进我的答案。
#include <sstream>
...
string lw(int a, int b) {
std::ostringstream o;
o << "lw $" << a << "0($" << b << ")\n";
return o.str();
}
#include <sstream>
string lw(int a, int b)
{
std::ostringstream os;
os << "lw $" << a << "0($" << b << ")\n";
return os.str();
}