String input isn't working

Here is the problem link: PROBLEM

#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    for (int x = 1; x <= t; ++x)
    {
        int n;
        cin >> n;
        vector <string> names(n);
        for (int i = 0; i < n; ++i) cin >> names[i];
        sort(names.begin(), names.end());
        int letters = -1;
        string leader;
        for (int i = 0; i < n; ++i)
        {
            set <char> chars;
            for (int j = 0; j < names[i].size(); ++j)
                if (names[i][j] != ' ')
                    chars.insert(names[i][j]);
            if (static_cast <int> (chars.size()) > letters)
            {
                letters = static_cast <int> (chars.size());
                leader = names[i];
            }
        }
        cout << "Case #" << x << ": " << leader << '\n';
    }
}

This works fine when there is no space in the input.
For example, if the input is

1
1
KICKSTART

then there are no issues.
But if the input is

1
1
GOOGLE KICKSTART

it only considers GOOGLE and ignores KICKSTART.
How do I fix this issue?

i think getline(cin,names[i]) is what you are looking for;
use it instead of cin>>names[i];

1 Like

use getline(cin,names[i])
as cin breaks at space

1 Like

@arpitpandey992 for some reason it messes up the code. When I try multiple test cases, it only runs the first one (that too wrongly). Suppose you have n=3, it will only read values up to n = 2.

ok, so after taking input for the integer n, you type a number (for n) and them press enter.
now, this enter key press is also considered a string char with no value by getline.
so, to overcome this, just place cin.ignore(); before taking input in string so that preceding enter presses are ignored.
like, cin>>n; cin.ignore(); getline(cin,arr[i]);
hope this helps

1 Like

Right after you get the test case input cin>>T; Use cin.ignore();

2 Likes

@akram01 @arpitpandey992 @mohitz_007 Thanks a lot. My code got accepted.

Glad to Help Bro