结构值无法在c ++中正确打印

Ali*_*786 0 c++ string struct c++11

我有一个String消息,我正在拆分字符串并将其存储在一个结构中.

 struct logMessage
 {
   int cefVersion;
   char *deviceVendor;
   char *deviceProduct;
   char *deviceVersion;
   int signatureID;
   char *eventName;
   int severity;
   char *objectIp;
   char *cs2;
   char *suser;
   int logonID;
   char *logonType;
}; 
Run Code Online (Sandbox Code Playgroud)

我已经拆分了字符串并将其存储在结构中,我的代码是这样的.

'split(string str)
{       
            string logmsg=str;
    logMessage lmsg;
    string delimiter = "|";
    size_t pos = 0;
    string token;
    int tokens=1;
    while ((pos = logmsg.find(delimiter)) != string::npos) {
            token = logmsg.substr(0, pos);
            cout <<"\n"<< token <<endl;
            logmsg.erase(0, pos + delimiter.length());

        switch(tokens){

                case 1:lmsg.cefVersion=atol((char *)token.c_str());
                   cout<<"\t token="<<token.c_str();
                   break;
                case 2:lmsg.deviceVendor=(char *)token.c_str();
                   cout<<"\t token="<<token.c_str()<<"\tlmsg.deviceVendor="<<lmsg.deviceVendor;
                   cout<<"\nmessage stored in the sturcture=deviceVendor:"<<lmsg.deviceVendor;
                   break;
                case 3:lmsg.deviceProduct=(char *)token.c_str();
                   cout<<"\nmessage stored in the sturcture=deviceProduct:"<<lmsg.deviceProduct;
                   cout<<"\t token="<<token.c_str()<<"\tlmsg.deviceProduct="<<lmsg.deviceProduct;break;
                case 4:lmsg.deviceVersion=(char *)token.c_str();
                   cout<<"\t token="<<token.c_str();break;
                case 5:lmsg.signatureID=atol((char *)token.c_str());
                   cout<<"\t token="<<token.c_str();break;
                case 6:lmsg.eventName=(char *)token.c_str();
                   cout<<"\t token="<<token.c_str();break;
                case 7:lmsg.severity=atol((char *)token.c_str());
                   cout<<"\t token="<<token.c_str();break;

                }   

        tokens++;
        cout<<"\ntokens="<<tokens;
        //#cout<<"\nmessage stored in the sturcture=deviceProduct:"<<lmsg.deviceProduct;    
    }   

    //#cout<<"\nmessage stored in the sturcture=cefVersion:"<<lmsg.cefVersion;
    //#cout<<"\nmessage stored in the sturcture=deviceProduct:"<<lmsg.deviceProduct;


    //#cout<<"\nmessage stored in the sturcture=signatureID:"<<lmsg.signatureID;
    //cout<<"\nmessage stored in the sturcture=eventName:"<<lmsg.eventName;
    //cout<<"\nmessage stored in the sturcture=severity:"<<lmsg.severity;
    logmsg=str;
             std::cout << logmsg << std::endl;
}'
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,注释#行无法正常工作,它正在打印其他一些值.除了这一切都很好,我不明白它为什么会发生.

And*_*ess 5

c_str()没有分配新的存储空间.文档说"通过进一步调用修改对象的其他成员函数,返回的指针可能会失效".

也就是说,每次重新分配令牌时,你已经存储在你结构中的char*都没有任何指向.

在填充它时,需要为每个结构字段分配一个新的char*字符串,并将tokenc_str()的strcpy分配给它.