将字符串指针连接到另一个字符串指针 C++
大家好,我有以下行:
string* playerInfo = "Name: " + firstName + " " + lastName + "\n" +
"Number: " + playerNumber + "\n" +
"Points: " + pointTotal + "\n";
其中firstName,lastName,playernumber,pointTotal都是字符串指针。
如何将它们全部放在另一个字符串指针中?编译器抱怨我的代码行。
抱歉,我不太擅长 C++,因为我有 Java 背景。
Hi everyone I have the following line:
string* playerInfo = "Name: " + firstName + " " + lastName + "\n" +
"Number: " + playerNumber + "\n" +
"Points: " + pointTotal + "\n";
where firstName, lastName, playernumber, pointTotal are all string pointers.
How can I put them all together into another string pointer? The compiler complains about my line of code.
Sorry, I'm not good with C++ I come from a Java background.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
少用指针。如果所有变量都只是字符串,那就行了。但既然你说你有指针:
从 Java 迁移到 C++ 时你应该打破的第一个习惯就是使用
new
创建所有对象。在C++中,new
不是用于创建对象,而是用于内存分配。任何时候您都应该使用局部变量而不是动态分配。当你不能时,尝试让一些库提供的对象(如 std::vector )为你处理分配和释放。Use less pointers. That would have worked if all your variables were just strings. But since you say you have pointers:
One of the first habits you should break when moving from Java to C++ is creating all your objects with
new
. In C++,new
is not for creating objects, it's for memory allocation. Any time you can use a local variable instead of dynamic allocation, you should. And when you can't, try to let some library-provided object likestd::vector
take care of the allocation and deallocation for you.为了像这样将一堆片段放在一起,我会使用字符串流,如下所示:
For putting a bunch of pieces together like this, I'd use a stringstream, something like this:
Java背景就是问题。
在 C++ 中你不能这样做。指针指向内存中的位置。它们位于不同的位置,因此您不能将它们连接起来。
为什么要使用字符串指针?您可能会对
char *
指针和string
感到困惑,其中 在STL中。您可能只想使用字符串,而不使用指针。你可以这样做:
你也可以使用+=。
但这很令人困惑,因为你不能这样做:
但你可以这样做:
所以我只是避免使用运算符 + 并使用 .append。
Java background is the problem.
You can't do this in C++. Pointers point to places in memory. They're in separate locations, so you can't just concatenate them.
Why are you using string pointers? You may be confused between
char *
pointers andstring
which is in the STL.You probably just want to use strings, without pointers. You can do it like this:
You can also use +=.
But this is confusing, because you CANNOT do:
But you can do:
So I just avoid the operator + and use .append.
您可能只想:
将
"Name"
放入std::string
然后创建一系列operator+()
调用,进而产生级联。您可能并不真正需要将playerInfo放在堆上,但如果您这样做,您可以拥有:
You probably want just:
Putting
"Name"
into astd::string
then creates a series ofoperator+()
calls that in turn produce the concatenation.You probably do not really need playerInfo to be on the heap, but if you do, you can have:
就像科芬先生使用“stringstream”的回答一样:
like Mr. Coffin´s answer using "stringstream":
正如您要求使用指针解决问题一样,这里是一个小学代码解决方案:
As you asked to solve your problem by using pointers here is an elementar school code solution: