[英]How to convert string to C-style string
我想用C ++讀取配置文件
我的代碼在這里:
#include <string>
#include <map>
using namespace std;
void read_login_data(char *login_data,map<string,string> &data_map);
#include <fstream>
#include <string>
#include <map>
#include "myutils.h"
using namespace std;
void read_login_data(char *login_data,map<string,string> &data_map)
{
ifstream infile;
string config_line;
infile.open(login_data);
if (!infile.is_open())
{
cout << "can not open login_data";
return false;
}
stringstream sem;
sem << infile.rdbuf();
while(true)
{
sem >> config_line;
while(config_line)
{
size_t pos = config_line.find('=');
if(pos == npos) continue;
string key = config_line.substr(0,pos);
string value = config_line.substr(pos+1);
data_map[key]=value;
}
}
}
#include <iostream>
#include <map>
#include "myutils.h"
using namespace std;
int main()
{
char login[] = "login.ini";
map <string,string> data_map;
read_login_data(login,data_map);
cout<< data_map["BROKER_ID"]<<endl;
char FRONT_ADDR[20]=data_map["BROKER_ID"].c_str();
cout << FRONT_ADDR<<endl;
}
配置文件是:
BROKER_ID=66666
INVESTOR_ID=00017001033
當我使用g++ -o test test.cpp
編譯它時,輸出是:
young001@server6:~/ctp/ctp_github/trader/src$ g++ -Wall -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:23:50: error: array must be initialized with a brace-enclosed initializer
如何將data_map["BROKER_ID"]
分配給FRONT_ADDR
?
我用過
strncpy(FRONT_ADDR, data_map["BROKER_ID"].c_str(), sizeof(FRONT_ADDR));
但是當我編譯它時,它說:
young001@server6:~/ctp/ctp_github/trader/src$ g++ -Wall -o test test.cpp
/tmp/cc5iIQ6k.o: In function `main':
test.cpp:(.text+0x70): undefined reference to `read_login_data(char*, std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&)'
collect2: ld returned 1 exit status
char FRONT_ADDR[20]=data_map["BROKER_ID"].c_str();
你不能這樣做。 您應該使用strncpy
(或copy_n
,但在這種情況下,您應該檢查, data_map["BROKER_ID"].c_str()
長度data_map["BROKER_ID"].c_str()
大於或等於n
)將一個char數組復制到另一個。
std::strncpy(FRONT_ADDR, data_map["BROKER_ID"].c_str(), sizeof(FRONT_ADDR));
當然,最好選擇使用std::string
:
std::string FRONT_ADDR = data_map["BROKER_ID"];
// and, anywhere you need const char*
somefunction(FRONT_ADDR.c_str());
嘗試這個,
char FRONT_ADDR[20]={0}; //all elements 0
std::strcpy(FRONT_ADDR, data_map["BROKER_ID"].c_str()); // assuming there is enough space in FRONT_ADDR
在C ++中,有一個內置方法( c_str()
)來進行轉換。 這是一個例子。
char* cs[10];
Qstring s("string");
cs = s.c_str();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.