Search code examples
c++arraysstringc++11int

convert string to array of integer in c++


Someone will help me, in understanding the while loop in following code about what it does? for example, take input from the user: 1 2 3 8 (input size not given) and one value (any index) show size of an array. it is printing the maximum value of the array. here the answer is 8.

#include<bits/stdc++.h>
#define ll long long 
using namespace std;
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        string x;
        getline(cin, x);
        ll p;
        istringstream iss(x);// use of this function
        vector<ll> v;
        ll ans;
        while(iss>>p)// what this loop do
        { 
           v.push_back(p);
        }
        ll size=v.size()-1;
        sort(v.begin(), v.end());
        if(size==v[size])
        {  
            ans=v[size-1];
        } 
        else
        {
            ans=v[size];
        }
        cout<<ans<<"\n";
    }
    return 0;
}

Solution

  • istringstream iss(x) creates a string stream called iss consisting of the string x. iss >> p extracts the next element from the iss stream and puts it into p. the return value is int because the variable p is of type int.

    while(iss>>p)           // get an int value from string stream iss
    { 
         v.push_back(p);    // push the int value to the vector
    }
    

    you have to use cin.ignore() after cin. otherwise the next getline function will take only new line character. like this:

    cin >> t;
    cin.ignore();