How to take unknown number of integers as input (without stringstream) using cin?

I was solving the Maximum Value (LOSTMAX Problem - CodeChef) problem where it is required to take an unknown number of integers as input and this is where I am stuck. I searched through the net and previous CodeChef discussions but could not find a short and efficient method to do so. I saw people suggesting to use scanf but I wanted to know that isn’t there any way to do so using cin (without using stringstream) and I even saw something like using while(cin >> x) but it simply doesn’t work, it goes on taking input? Please help.

@everule1 Please help. You have proved to be very helpful along with some other users like @ssjgz.

Idk, At best you can manually seperate the string by spaces. Input the line by using

getline(cin,strname);

sometimes python is the way to go

for _ in range(int(input())):
    seq=list(map(int,input().split()))
    seq.remove(len(seq)-1)
    print(max(seq))

Thanks @everule1 but I am currently refining my C++ skills so I wanted to know if anything could be done using C++. Although I did try using stringstream but I see some strange behaviour.

While using stringstream, after taking the number of testcases as input the program simply skips one line and begins to take input after that thus if I enter t = 3 and then use a loop, the program accepts only 2 lines of integers.

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

int main()
{
    int t;
    cin >> t;

    for(int i=0; i<t; i++)
    {
        string str;
        stringstream ss;

        getline(cin, str);
        ss << str;

        vector<int> num;
        int temp;
        while(!(ss.eof()))
        {
            if(ss >> temp)
                num.push_back(temp);
        }
        for(auto i : num)
            cout << i << " ";
        cout << "\n";
    }
    return 0;
}

@everule1 Try running the above code and see the anomaly.

I don’t know how stringstream works :neutral_face:.
I just parsed the input string and stored the numbers i a multiset, removed n and outputted the largest element.
https://www.codechef.com/viewsolution/30552515
If you want to know about stringstreams just ask @ssjgz.
Oh wait, I don’t know exactly how it works, but you didn’t ignore the first line.
just type cin.ignore() right after inputting ‘t’.
here, corrected your code
https://www.codechef.com/viewsolution/30552635

1 Like

Thanks @everule1 , cin.ignore() actually solved the problem.

@ssjgz can you please explain a bit about stringstream in this context and the use of cin.ignore()?

I know cin.ignore() puts the input reader on the next line.

Then why is it that we don’t use cin.ignore() in other cases?

Because when it runs out of input and you try to take an input, the reader automatically goes to the next line. With cin.ignore() it ignores the rest of the line.

3 Likes

Thanks!