1

spoj question .unable to find error in solution. pls help

Given a sequence of 2*k characters, please print every second character from the first half of the sequence. Start printing with the first character.

Input In the first line of input your are given the positive integer t (1<=t<=100) - the number of test cases. In the each of the next t lines, you are given a sequence of 2*k (1<=k<=100) characters.

Output For each of the test cases please please print every second character from the first half of a given sequence (the first character should appear).

Input: 4 your progress is noticeable

Output: y po i ntc

my solution getting "extra space" hence wrong result

#include<iostream>
#include<string>
using namespace std;

void halfHalf(string ch){   
    int size=ch.size();
    for(int i=0;i<size/2;i+=2){
        cout<<ch[i];
        }
    cout<<endl;
}

int main() {
    string name[50];
    int numLine,i(0);
    cin>>numLine;

    while(i<=numLine){
        getline(cin,name[i]);
        halfHalf(name[i]);
        i++;
    }
return 0;
}

enter image description here enter image description here

1 Answers1

2

You need cin.ignore() after reading the first integer. This works for me

#include <bits/stdc++.h>
using namespace std;

int main() {
    int T;
    cin >> T;
    cin.ignore();
    while (T--) {
        string s;
        getline(cin, s);
        for (int i = 0; i * 2 < s.size(); i += 2)
            cout << s[i];
        cout << endl;
    }
    return 0;
}

DEMO

This answer should be useful. It quotes

If you're using getline after cin >> something, you need to flush the newline out of the buffer in between.

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
Community
  • 1
  • 1
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50