1

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'; 
10
  • 2
    It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: How to debug small programs Commented Sep 27, 2017 at 16:30
  • @NathanOliver Thanks! An answer here will be very helpful also. Commented Sep 27, 2017 at 16:31
  • 5
    The range based for does not work as you expect: It does not iterate with a running index, but the elements of the container. In your case, the actual characters of the string Commented Sep 27, 2017 at 16:33
  • @king_nak Can you kindly elaborate it a bit and recommend a fix, please? A reference to another webpage where I can find a clear instruction of how to do it will also be very helpful. Commented Sep 27, 2017 at 16:55
  • Since you don't really benefit from the range based for loop I would just use a regular for loop with j being the index. for(int j = 0; j < S.length(); ++j) { ... } Commented Sep 27, 2017 at 16:56

1 Answer 1

1

The range-based for loop iterates over the elements of a container. 'j' in your code is a character in the string, not an index. Try this:

for (auto character : S) { if (even.length() > odd.length()) { odd.push_back(character); } else { even.push_back(character); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

That is a very clever implementation of even and odd, imo! Thank you! Yes, it clarified my confusion also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.