-1

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;
}
Posi2
  • 144
  • 1
  • 14
  • My friend has a better explanation for that have a look https://stackoverflow.com/questions/7663709/convert-string-to-int-c – joeydash Nov 13 '17 at 08:04
  • You should ignore one character from cin, so you can enter string properly. use cin.ignore(); after cin >> t; :) – Jay Joshi Nov 13 '17 at 09:20
  • Possible duplicate of [Convert string to int C++](https://stackoverflow.com/questions/7663709/convert-string-to-int-c) –  Apr 30 '18 at 03:33

3 Answers3

3

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();
Jay Joshi
  • 868
  • 8
  • 24
1
    string str;
    cin>>str;
    int size = str.size(),arr[size];  //array of size equal to string size
    for(int i=0;i<size;i++)
    {
        arr[i] = (int)str[i]-'0';    //typecasting to int
    }

for str[i]-'0' the explanation is : What is the purpose of using str[i]-'0' where str is a string? Error may occur if unable to typecast

omkar
  • 71
  • 1
  • 6
0

Using function stoi() (for int values) or stol()(for long values) also optionfor integer values.

int n=56; // use #include<bits/stdc++.h>
string s=to_string(n); // we get string "56" that's for integer to string
int x=stoi(substr(index,length));// for string to integer
Posi2
  • 144
  • 1
  • 14