Using StringStream for input

So I was solving this problem, And I see people have been using stringstream for input. Can somebody help me understand how it works.

int main()
{
    ios_base :: sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    freopen("error.txt","w",stderr);
    #endif
 
    ll t,n,l,r,q,val;
    string str;
        
        cin >> n;
        for(ll i=0 ; i<n ; i++) cin >> arr[i];
 
        memset(lazy , 0 , sizeof(lazy));
        build(1,0,n-1);
        
        cin >> q;
        getline(cin, str);
        while(q--)
        {
            getline(cin, str);
		    stringstream ss(str);
		    ss >> l >> r;
            if(ss >> val) 
            { 
               if(l<=r)
               update_range(1,0,n-1,l,r,val) ;
               else { update_range(1,0,n-1,0,r,val); update_range(1,0,n-1,l,n-1,val); } 
            }
            else 
            {
               if(l<=r)
               cout << query(1,0,n-1,l,r) << endl;
               else cout << min(query(1,0,n-1,0,r),query(1,0,n-1,l,n-1)) << endl;
            }
        } 
 
    return 0;
} 

I kind of get the gist but why do we need getline() before while(q--). Removing it gives SIGSEV error.

Thanks.

Even after inputting t, you are still on the first line. But the input starts fron the second line.

2 Likes