Search code examples
c++cin

Stop input loop when input is done | std::cin


I want to write a function that gets a set of integers and saves them to a vector.

To get the integers I'm using a while loop.

Enter the vector elements: 1 2 3 4 5

I want the loop to stop looking for input after the last element is inputted or until a non-numberis inputted, however I'm having trouble with it.

It is an assignment, so it needs to read input from std::cin.

This is my code:

#include <iostream>
#include <vector>

bool NumInVect(int num, std::vector<int> vect)
{
  bool numInVect = false;
  for (int i = 0; i < vect.size(); i++)
    {
      if (vect[i] == num)
      {
        numInVect = true;
      }
    }
  return numInVect;
}

int main() {
  std::vector<int> tempVect;
  std::vector<int> finalVector;
  
  std::cout << "Enter the vector elements: ";
  
  int currVal;
  
  
  while (std::cin >> currVal)
  {
    std::cout << "-\n";
    
    if (!NumInVect(currVal, tempVect))
    {
      tempVect.push_back(currVal);
    }
    std::cout << currVal << std::endl;

  }

//the code never reaches this loop, since its stuck in the while loop
std::cout << "knak\n";
  for (int i = 0; i < tempVect.size(); i++)
    {
      std::cout << tempVect[i];
    }
  
}

I've tried doing multiple things like using std::cin.eof()/.fail(), std::cin >> currVal in the while loop, a do-while loop, but I can't seem to figure out how to get this to work. Does anyone have any tips on what to look into or how to approach this?


Solution

  • If your intention is to get all the input from a given line, and add individual numbers to the vector, then you want to read a line of input into a string, then use an istringstream to process that line of input.

    A simplified example:

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <vector>
    
    int main() {
        std::vector<int> tempVect;
        std::string line;
        std::getline( std::cin, line );
    
        std::istringstream iss( line );
        int curVal;
        while ( iss >> curVal ) {
            tempVect.push_back( curVal );
        }
    }