I'm trying to read integers from the console into my vector of ints. I want to keep reading in integers from a single line until the user clicks enter. I've been trying to use getline and stringstream, but it keeps looking for input after I press enter. Any solutions?
A high-level description: This program reads in numbers from the console and pushes them to the back of a vector. The vector is then sorted and two pointers are created to point to the back and front. The user can then enter a sum that the program will then search for in linear time by taking the sum of the two pointers. The pointers will then keep moving in one direction until they either find such a sum or determine that no such sum exists.
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
int findSum(vector<int> tempVec, int sum)
{
int i;
cout << "Sorted sequence is:";
for ( i = 0; i < tempVec.size(); i++ )
cout << " " << tempVec[i];
cout << endl;
int *ptr1 = &tempVec[0];
cout << "ptr1 points to: " << *ptr1 << endl;
int *ptr2 = &tempVec[tempVec.size() - 1];
cout << "ptr2 points to: " << *ptr2 << endl;
int count = 0;
while ( ptr1 != ptr2 )
{
if ( (*(ptr1) + *(ptr2)) == sum )
{
cout << *(ptr1) << " + " << *(ptr2) << " = " << sum;
cout << "!" << endl;
return count;
}
if ( (*(ptr1) + *(ptr2)) < sum)
{
cout << *(ptr1) << " + " << *(ptr2) << " != " << sum;
ptr1 = ptr1 + 1;
cout << ". ptr1 moved to: " << *ptr1 << endl;
count++;
}
else
{
cout << *(ptr1) << " + " << *(ptr2) << " != " << sum;
ptr2 = ptr2 - 1;
cout << ". ptr2 moved to: " << *ptr2 << endl;
count++;
}
}
return -1;
}
int main()
{
int ValSum;
cout << "Choose a sum to search for: ";
cin >> ValSum;
vector<int> sumVector;
int input;
cout << "Choose a sequence to search from: ";
while ( cin >> input != "\n" )
{
//getline(cin, input);
if ( cin == '\0' )
break;
sumVector.push_back(input);
}
sort(sumVector.begin(), sumVector.end());
int count = findSum(sumVector,ValSum);
if ( count == -1 )
cout << "\nThe sum " << ValSum << " was NOT found!" << endl;
else
{
cout << "\nThe sum " << ValSum << " was found!" << endl;
cout << count + 1 << " comparisons were made." << endl;
}
sumVector.clear();
}