Star Rider Star Rider - 26 days ago 11
C++ Question

Why my string isn't taking the input correctly the second time?

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

Answer

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'.

Comments