Thangaraj
Thangaraj

Reputation: 3184

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 one = "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?

Upvotes: 0

Views: 349

Answers (2)

BrandonSun
BrandonSun

Reputation: 129

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

Upvotes: 2

Legolas
Legolas

Reputation: 1502

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?

Upvotes: 1

Related Questions