mercredi 27 septembre 2017

Confusion regarding range-based for loop in C++

This code takes a string and then write outs the even and odd-positioned characters of the string as 2 separate strings separated by a space. I have solved the problem using standard for loop. But I am trying to use range-based for loop in it instead of the normal for loop (after getting fired up by Bjarne's 2017 CPPCON keynote). The normal for loop works fine and I have commented it in the following code-block.

Problem is: The code compiles with g++ -std=c+11 command, but the even and odd strings are coming out garbled and reads like binary files. Can you please explain what I am doing wrong and exactly what is happening here? A clear explanation will be much appreciated. Thank you.

    string S,even,odd;
    cout << "Enter a string:\n";
    cin.ignore();   // So that getline does not catch 
    //the eol character
    getline(cin,S);
    // for (int j=0; j<S.length(); j++){
    //     if(j==0 || j%2==0){even.push_back(S[j]);}
    //     else {odd.push_back(S[j]);}
    // }
    for (auto j : S){
        if(j==0 || j%2==0){even.push_back(S[j]);}
        else {odd.push_back(S[j]);}
    }
    cout << "You wrote: " << S <<'\n';
    cout << "Even(including 0) positioned character(s) 
    of " << S << " is(are) " << even <<'\n';
    cout << "Odd positioned character(s) of " << S << 
    " is(are) " << odd <<'\n';

Aucun commentaire:

Enregistrer un commentaire