将文本添加到 char*
是否可以向 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题被标记为C++,因此请使用C++。摆脱
char*
并使用std::string
:您可以通过分配足够大的新数组来“添加”两个字符数组(char*)保存两者,并将两个字符串复制到新数组中。我想您会同意 std::string 更容易,但它也为您提供了更少的机会在代码中引入微妙的错误,从而使调试和维护变得更简单。
Your question is tagged with C++, so use C++. Get rid of your
char*
's and usestd::string
: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.您必须首先分配内存,例如:
然后使用
strcpy
和strcat
,但是..您有标签c++
。 请使用std::string
或
如果
name
不是const char*
,而是std::, Note string
,不需要显式转换,所以参考meagar的帖子You must allocate the memory first, for example:
and then use
strcpy
andstrcat
, but .. you have tagc++
. Usestd::string
or
Note if
name
is notconst char*
, butstd::string
, you don't need from explicit conversions, so refer to meagar's post您还可以使用 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.