I am trying to create a connection to a postgres database from C++ and ask for the password from the user. 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.
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? , 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
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
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.