c++ - Why my string isn't taking the input correctly the second time? -
my code takes string , displays index position letters after space shows odd indexed letters. if give input hacker
should give hce akr
. here code isn't giving me right answer second input. on giving 2nd input rank
should give rn ak
. instead of gives k
.here 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) { = + a[i]; } else { odd = odd + a[i]; } } cout << << " " << odd << "\n";//<<<<<<i think \n //problem need \n.i obeserved on removing \n, codes // works correctly. } int main() { /* enter code here. read input stdin. print output stdout */ string str; int t; cin >> t; for(int i=0; < t; i++) { std::cin.ignore(); getline(cin, str); f(str); } return 0; }
you should move std::cin.ignore()
outside of loop. getline consumes newline character, first input leaves (cin>>t
).
when read e.g. int or char, newline character after input stays in input stream. doing getline read newline character , call cin.ignore()
consume newline character. each getline()
consumes whole line including newline character, don't have call cin.ignore()
, if do, per default consume 1 character, here 'r'.
Comments
Post a Comment