C++ 字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21528432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:41:20  来源:igfitidea点击:

C++ String concatination

c++string

提问by backspace

I have realised my mistake. I was trying to concatenate two strings.

我已经意识到我的错误了。我试图连接两个字符串。

Thanks for help!

感谢帮助!

I have just started to c++. I have a problem about string contamination. I don't have problem when I use:

我刚刚开始使用 C++。我有关于字符串污染的问题。我使用时没有问题:

cout <<"Your name is"<<name;

But when I try to do it with string:

但是当我尝试用字符串来做时:

string nametext;
nametext = "Your name is" << name;
cout << nametext;

I got an error. How can I concatenate two strings?

我有一个错误。如何连接两个字符串?

Thanks you!

谢谢!

回答by Creris

For string concatenation in C++, you should use the +operator.

对于 C++ 中的字符串连接,您应该使用+运算符。

nametext = "Your name is" + name;

回答by Vlad from Moscow

First of all it is unclear what type name has. If it has 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), bacause character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write

如果 name 是一个字符数组,那么您不能对两个字符数组使用运算符 +(字符串文字也是一个字符数组),因为表达式中的字符数组会被编译器隐式转换为指针。在这种情况下,你可以写

std::string nametext( "Your name is " );
nametext.append( name );

or

或者

std::string nametext( "Your name is " );
nametext += name;

回答by eerorika

nametextis an std::stringbut these do not have the stream insertion operator (<<) like output streams do.

nametext是一个,std::string但它们<<不像输出流那样具有流插入运算符 ( )。

To concatenate strings you can use the appendmember 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成员函数(或它的等效函数+=,以完全相同的方式工作)或+运算符,它通过连接前两个函数创建一个新字符串。

回答by Georgios

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;
}

回答by Minhaj Arfin

nametext = "Your name is" + name;

nametext = "Your name is" + name;

I think this should do

我认为这应该做