1

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;

        }
    }


}

test.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
4

3 に答える 3

3
char FRONT_ADDR[20]=data_map["BROKER_ID"].c_str();

これはできません。char の 1 つの配列を別の配列にコピーするにはstrncpy(またはcopy_n、ただしこの場合は、 の長さdata_map["BROKER_ID"].c_str()が より大きいか等しいことを確認する必要があります)を使用する必要があります。n

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());
于 2013-05-24T02:04:29.897 に答える
0

C++ にc_str()は、変換を行う組み込みの method( ) があります。これが例です。

char* cs[10];
Qstring s("string");
cs = s.c_str();
于 2013-05-24T02:44:01.497 に答える