0

Here is a question of C++ that I was practising on some other site. The code is given below. My code fails for multiple inputs. the output is only

clee olg  

instead of

clee olg
sho col

Problem statement :

Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as space-separated strings on a single line.

INPUT- The first line contains an integer, t (the number of test cases). Each line i of the subsequent lines contain a String, S

OUTPUT- For each String S (where 0<= j<=N-1), print S's even-indexed characters, followed by a space, followed by S's odd-indexed characters.

Eg-

2
college
school

output-

clee olg
sho col

code :

int main() 
{
    int t;
    cin>>t;
    string str;
    vector<string>s_even;
    vector<string>s_odd;
    for(int i=0;i<t;i++)
    {
        getline(cin,str);

        for(int j=0;j<str.size();j++)
        {        
            if(j%2==0)
                 { 
                   string  a;
                   a=str[j];
                   s_even.push_back(a);

                 }
             else
                 { 
                   string b;
                   b= str[j];
                   s_odd.push_back(b);
                  }
           }

copy(s_even.begin(),s_even.end(),ostream_iterator<string>(cout));

cout<<" ";

copy(s_odd.begin(),s_odd.end(),ostream_iterator<string>(cout));

 str.clear();
 s_odd.clear();
 s_even.clear();
 }
 return 0;

}       
Sander De Dycker
  • 15,403
  • 1
  • 31
  • 37
  • 4
    https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction?rq=1 – Mat Jul 23 '18 at 09:40
  • Possible duplicate of [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Caleth Jul 23 '18 at 10:36
  • Simplest fix: `std::cin >> t >> std::ws;` where you read in the count – Caleth Jul 23 '18 at 10:37
  • Aside: You don't need `std::vector`s, you can just `push_back` into a single string. You can then `std::cout << evens << " " << odds << std::endl;` – Caleth Jul 23 '18 at 10:41

1 Answers1

0

When debugging it might be helpful to print out your intermediate results. This can help you pinpoint the source of failure. For example if you had printed out str after your getline(cin, str), you'll notice that your first iteration gives you an empty string.

As for why, and the solution, check out the link here by @Mat

Tomforge
  • 72
  • 1
  • 8