简体   繁体   English

如何将用户输入的char *追加到const char *的初始化中

[英]How to append a user inputted char* to the initialization of a const char*

I am trying to create a connection to a postgres database from C++ and ask for the password from the user. 我正在尝试从C ++创建到Postgres数据库的连接,并要求用户输入密码。 Here is the code in question: 这是有问题的代码:

    char* pass;
    cout << "Please enter password for user: Mickey" << endl;
    cin >> pass;

    const char *connectInfo = "host=cs-linux dbname=gbianchet user=mickey password=" + pass;

I am wondering how I can get the user's input and append it to the end of the the initialization for connectInfo. 我想知道如何获取用户输入并将其附加到connectInfo初始化的末尾。

I have searched for the answer to this question and have found these links, Initialize const char* by concatenating another char* and How to cleanly use: const char* and std::string? 我已经搜索了该问题的答案,并找到了以下链接: 通过串联另一个char * 初始化const char *以及如何干净地使用:const char *和std :: string? , but they don't quite answer my question. ,但他们并未完全回答我的问题。

Any help would be much appreciated. 任何帮助将非常感激。

Thanks 谢谢

The references you gave in your question are actually not appending or concatenating in const char * they used Preprocessor Directives 您在问题中给出的引用实际上不是在const char *附加或串联const char *他们使用了预处理程序指令

This is the easy and proper way to achieve the same thing 这是实现同一目标的简单而正确的方法

string pass;
cout << "Please enter password for user: Mickey" << endl;
getline(cin, pass);
string connectionString("host=cs-linux dbname=gbianchet user=mickey password=" + pass);
const char *connectInfo = connectionString.c_str();

include string class header in your source code as #include <string> string class is in std namespace 在源代码中包含字符串类标头,因为#include <string> 字符串类在std名称空间中

http://www.cplusplus.com/reference/string/string/c_str/ http://www.cplusplus.com/reference/string/string/c_str/

Create your desired string using c++ string and then call the method .c_str() (see the above link) 使用c ++字符串创建所需的字符串,然后调用方法.c_str()(请参见上面的链接)

For a given c++ string, it'll return you a NULL terminated c-string version of the c++ string that you can pass to your function that expects a c-string. 对于给定的c ++字符串,它将返回给您NULL终止的c ++字符串版本的c ++字符串,您可以将其传递给需要c字符串的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM