0

My code takes a string and displays the even index position letters then after a space it shows the odd indexed letters. Like if i give an input Hacker it should give Hce akr. Now here my code isn't giving me the right answer for the second input. Like on giving the 2nd input as Rank it should give Rn ak. Instead of that it gives an k .Here it misses R.


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void f(string a) {

    string odd,even;
    for(int i=0; a[i] != '\0'; i++) {
        if(i % 2 == 0) {
            even = even + a[i];
        } else {
            odd = odd + a[i];
        }
    }

    cout << even << " " << odd << "\n";//<<<<<<I THINK THIS \n IS THE 

      //PROBLEM BUT I NEED THIS \n.I OBESERVED THAT ON REMOVING \n, CODES
      // WORKS CORRECTLY.
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    string str;
    int t;
    cin >> t;

    for(int i=0; i < t; i++) {
        std::cin.ignore();
        getline(cin, str);
        f(str);
    }

    return 0;
}
Klaus
  • 24,205
  • 7
  • 58
  • 113
Star Rider
  • 107
  • 1
  • 6
  • 4
    Use `i != a.size()` instead as the condition, `a[i] != '\0'` is a bit dodgy – M.M Nov 08 '16 at 13:14
  • 1
    Possible duplicate of [cin and getline skipping input](http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input), check which ignore parameters to use. – stefaanv Nov 08 '16 at 13:22

1 Answers1

3

You should move the std::cin.ignore() outside of the loop. The getline consumes the newline character, just the first input leaves it (cin>>t).

When you read e.g. an int or a char, the newline character after the input stays in the input stream. Thus now doing a getline would just read the newline character and you call cin.ignore() to consume the newline character. But then each getline() consumes the whole line including the newline character, so you don't have to call cin.ignore() and if you do, it will per default consume one character, here the 'R'.

yassin
  • 642
  • 2
  • 7
  • 18
  • thanks for your solution , but i don't understand why it was giving me wrong earlier. – Star Rider Nov 08 '16 at 13:17
  • 1
    Because after the first word from the input, the ignore() (in the loop) caused the next character, the 'R' from Rank, to be ignored. – Rene Nov 08 '16 at 13:21