[英]C++ String Concatenation operator<<
I have realised my mistake.我已经意识到我的错误了。 I was trying to concatenate two strings.我试图连接两个字符串。
I have just started to learn C++.我刚刚开始学习 C++。 I have a problem about string concatenation.我有关于字符串连接的问题。 I don't have problem when I use:我使用时没有问题:
cout << "Your name is"<<name;
But when I try to do it with a string:但是当我尝试用字符串来做时:
string nametext;
nametext = "Your name is" << name;
cout << nametext;
I got an error.我有一个错误。 How can I concatenate two strings?如何连接两个字符串?
对于 C++ 中的字符串连接,您应该使用+
运算符。
nametext = "Your name is" + name;
First of all it is unclear what type name has.首先,不清楚类型名称有什么。 If it has the type std::string
then instead of如果它的类型为std::string
则代替
string nametext;
nametext = "Your name is" << name;
you should write你应该写
std::string nametext = "Your name is " + name;
where operator + serves to concatenate strings.其中 operator + 用于连接字符串。
If name
is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler.如果name
是字符数组,那么您不能对两个字符数组使用运算符 +(字符串文字也是字符数组),因为表达式中的字符数组会被编译器隐式转换为指针。 In this case you could write在这种情况下,你可以写
std::string nametext( "Your name is " );
nametext.append( name );
or或者
std::string nametext( "Your name is " );
nametext += name;
nametext
is an std::string
but these do not have the stream insertion operator ( <<
) like output streams do. nametext
是一个std::string
但它们没有像输出流那样的流插入运算符 ( <<
)。
To concatenate strings you can use the append
member function (or its equivalent, +=
, which works in the exact same way) or the +
operator , which creates a new string as a result of concatenating the previous two.要连接字符串,您可以使用append
成员函数(或其等效的+=
,其工作方式完全相同)或+
运算符,它会创建一个新字符串作为连接前两个的结果。
You can combine strings using stream string like that:您可以使用这样的流字符串组合字符串:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string name = "Bill";
stringstream ss;
ss << "Your name is: " << name;
string info = ss.str();
cout << info << endl;
return 0;
}
nametext = "Your name is" + name;
我认为这应该做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.