gpt4 book ai didi

c++ - 如何将字符串转换为C风格的字符串

转载 作者:行者123 更新时间:2023-11-30 01:58:53 26 4
gpt4 key购买 nike

我想使用 C++ 读取配置文件

我的代码在这里:

myutils.h

#include <string>
#include <map>
using namespace std;

void read_login_data(char *login_data,map<string,string> &data_map);

myutils.cpp

#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;

}
}


}

测试.cpp:

#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() 的长度大于或等于 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());

关于c++ - 如何将字符串转换为C风格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16726630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com