将文本添加到 char*

发布于 2024-10-03 03:39:38 字数 181 浏览 4 评论 0原文

是否可以向 char* 添加文本?

因为这段代码给出了错误:

name3 = "SELECT account_id FROM players WHERE name = '" + name + "'";

(name3 = a char*)

Is it possible to add text to a char*?

Because this code gives errors:

name3 = "SELECT account_id FROM players WHERE name = '" + name + "'";

(name3 = a char*)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓝天白云 2024-10-10 03:39:38

您的问题被标记为C++,因此请使用C++。摆脱 char* 并使用 std::string

std::string name = "...";

std::string name3 = "SELECT account_id FROM players WHERE name = '" + name + "'";

您可以通过分配足够大的新数组来“添加”两个字符数组(char*)保存两者,并将两个字符串复制到新数组中。我想您会同意 std::string 更容易,但它也为您提供了更少的机会在代码中引入微妙的错误,从而使调试和维护变得更简单。

Your question is tagged with C++, so use C++. Get rid of your char*'s and use std::string:

std::string name = "...";

std::string name3 = "SELECT account_id FROM players WHERE name = '" + name + "'";

You can "add" two character arrays (char*'s) by allocating a new array large enough to hold both, and copying both strings into the new array. I think you'll agree that std::string is easier, but it also provides less opportunity for you to introduce subtle errors into your code making debugging and maintenance simpler down the road.

夏末 2024-10-10 03:39:38

您必须首先分配内存,例如:

char* name = new char[ BUFF_SIZE ];

然后使用strcpystrcat,但是..您有标签c++。 请使用 std::string

std::string name3 = "SELECT account_id FROM players WHERE name = '"
                    + 
                    std::string( name ) 
                    + 
                    "'";

std::string name3 = "SELECT account_id FROM players WHERE name = '";
name3 += name;
name3 += "'"; // or name3.push_back( ';' );

如果 name 不是 const char*,而是 std::, Note string,不需要显式转换,所以参考meagar的帖子

You must allocate the memory first, for example:

char* name = new char[ BUFF_SIZE ];

and then use strcpy and strcat, but .. you have tag c++. Use std::string

std::string name3 = "SELECT account_id FROM players WHERE name = '"
                    + 
                    std::string( name ) 
                    + 
                    "'";

or

std::string name3 = "SELECT account_id FROM players WHERE name = '";
name3 += name;
name3 += "'"; // or name3.push_back( ';' );

Note if name is not const char*, but std::string, you don't need from explicit conversions, so refer to meagar's post

聆听风音 2024-10-10 03:39:38

您还可以使用 sprintf 来描述您所描述的内容。

另外,如果这是用于数据库连接,您可能需要考虑使用准备好的语句。

You can also use sprintf for what you're describing.

Also, if this is for a database connection you may want to consider using prepared statements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文