开发者

substr in c++ problem

When I try to execute the program, the output is coming as expected for the first iteration. but for second iteration, out is not coming as expected...

int main(){
        string insertBuffer;
        string valSep;
        valSep = ":";
        string configParamSep = "\r\n";
        int configParamSepSize = 2;
        string configParam;
        string::size_type mCPos = 0;
        string::size_type mCBeginPos = 0;
    int finished = 0;
    string o开发者_开发知识库ne = "hai: yes";
    string two = "tension: no"; 
        insertBuffer = one + "\r\n" + two + "\r\n";

    cout<<"OUTPUT:"<<"\n";

        while (!finished){
                if( !(mCBeginPos >= insertBuffer.length()) && ((mCPos = insertBuffer.find(valSep,mCBeginPos)) != string::npos)){
                        configParam = insertBuffer.substr(mCBeginPos,mCPos);
                }else{
                        finished = 1;
                        break;
                }
        cout<<configParam<<"\n";
                mCBeginPos = mCBeginPos + insertBuffer.find(configParamSep,mCBeginPos) + configParamSepSize;
    }

    return 0;
}

OUTPUT:

hai
tension: no

But expected outpu is:-

hai
tension

Any clue why this is happening?


basic_string<CharType, Traits, Allocator> substr(
    size_type _Off = 0,
    size_type _Count = npos
) const;

The 2nd parameter is not end index.

A simple fix: configParam = insertBuffer.substr(mCBeginPos,mCPos - mCBeginPos);


From this link http://en.cppreference.com/w/cpp/string/basic_string/substr I read that the second parameter is a count and not a position. Does that help, or am I wrong here?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜