[英]How to append a user inputted char* to the initialization of a const char*
我正在嘗試從C ++創建到Postgres數據庫的連接,並要求用戶輸入密碼。 這是有問題的代碼:
char* pass;
cout << "Please enter password for user: Mickey" << endl;
cin >> pass;
const char *connectInfo = "host=cs-linux dbname=gbianchet user=mickey password=" + pass;
我想知道如何獲取用戶輸入並將其附加到connectInfo初始化的末尾。
我已經搜索了該問題的答案,並找到了以下鏈接: 通過串聯另一個char * 來 初始化const char *以及如何干凈地使用:const char *和std :: string? ,但他們並未完全回答我的問題。
任何幫助將非常感激。
謝謝
您在問題中給出的引用實際上不是在const char *
附加或串聯const char *
他們使用了預處理程序指令
這是實現同一目標的簡單而正確的方法
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>
字符串類在std
名稱空間中
http://www.cplusplus.com/reference/string/string/c_str/
使用c ++字符串創建所需的字符串,然后調用方法.c_str()(請參見上面的鏈接)
對於給定的c ++字符串,它將返回給您NULL終止的c ++字符串版本的c ++字符串,您可以將其傳遞給需要c字符串的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.