How to make a while loop till there is something to be readen c++

59 views Asked by At

I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:

The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.

Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.

However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.

I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.

CODE:

 #include <iostream>
 #include <string>
 #include<vector>
 #include <sstream>
 #include <cmath>
 #include <string.h>
 #include <stdio.h>
 #include <climits>

 using namespace std;

 const int length = 17000;
 int power(int x){
int sum =2;
for(int i = 0;i<x;i++)  {
    sum *= 2;
}   
return sum;
}
bool ison(int i,int x)
{
 if((i>>x) & 1)return true;
return false;
}
int main()
{


while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {

        Vec.push_back(cur);
        if (cin.get() == '\n') {
            break;
        }
}

int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];

for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
 }
  int index=0;


for(int i=1;i<length;i++)
{  
   for(int j=0;j<Vec.size();j++)
   {
      if(ison(i,j))
      {
         sumOfarr1[index]+=Vec[j];

      }
      else
      {
         sumOfarr2[index]+=Vec[j];

      }
   }index++;
}
int ans=INT_MAX;
int ii;
 for(int i=0;i<index;i++)
{
   if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
  {
     ii=i;
     ans=abs(sumOfarr1[i]-sumOfarr2[i]);
  }
  }   
 if(sumOfarr1[ii]<sumOfarr2[ii]){
     cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
 }
else{
    cout << sumOfarr2[ii] << " " << sumOfarr1[ii];  
}

cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
 Vec.clear();

     }  

  return 0;
 }
1

There are 1 answers

0
JohnSmith911991 On

Yes I found the solution just using getline and stringstream.

aka this

    vector<int> Vec;

 string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}