How to cin values into a vector

258,167

Solution 1

As is, you're only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace

cin >> input;
V.push_back(input);

with

while (cin >> input)
    V.push_back(input);

What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:

while ((cin >> input) && input != 9999)
    V.push_back(input);

will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.

Solution 2

You need a loop for that. So do this:

while (cin >> input) //enter any non-integer to end the loop!
{
   V.push_back(input);
}

Or use this idiomatic version:

#include <iterator> //for std::istream_iterator 

std::istream_iterator<int> begin(std::cin), end;
std::vector<int> v(begin, end);
write_vector(v);

You could also improve your write_vector as:

 #include <algorithm> //for std::copy

template <typename T>
void write_vector(const vector<T>& v)
{
   cout << "The numbers in the vector are: " << endl;
   std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}

Solution 3

Other answers would have you disallow a particular number, or tell the user to enter something non-numeric in order to terminate input. Perhaps a better solution is to use std::getline() to read a line of input, then use std::istringstream to read all of the numbers from that line into the vector.

#include <iostream>
#include <sstream>
#include <vector>

int main(int argc, char** argv) {

    std::string line;
    int number;
    std::vector<int> numbers;

    std::cout << "Enter numbers separated by spaces: ";
    std::getline(std::cin, line);
    std::istringstream stream(line);
    while (stream >> number)
        numbers.push_back(number);

    write_vector(numbers);

}

Also, your write_vector() implementation can be replaced with a more idiomatic call to the std::copy() algorithm to copy the elements to an std::ostream_iterator to std::cout:

#include <algorithm>
#include <iterator>

template<class T>
void write_vector(const std::vector<T>& vector) {
    std::cout << "Numbers you entered: ";
    std::copy(vector.begin(), vector.end(),
        std::ostream_iterator<T>(std::cout, " "));
    std::cout << '\n';
}

You can also use std::copy() and a couple of handy iterators to get the values into the vector without an explicit loop:

std::copy(std::istream_iterator<int>(stream),
    std::istream_iterator<int>(),
    std::back_inserter(numbers));

But that’s probably overkill.

Solution 4

you have 2 options:

If you know the size of vector will be (in your case/example it's seems you know it):

vector<int> V(size)
for(int i =0;i<size;i++){
    cin>>V[i];
 }

if you don't and you can't get it in you'r program flow then:

int helper;
while(cin>>helper){
    V.push_back(helper);
}

Solution 5

If you know the size of the vector you can do it like this:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (auto &it : v) {
        cin >> it;
    }
}
Share:
258,167
Sean
Author by

Sean

Updated on March 23, 2022

Comments

  • Sean
    Sean about 2 years

    I'm trying to ask the user to enter numbers that will be pushed into a vector, then using a function call to count these numbers.

    why is this not working? I'm only able to count the first number.

    template <typename T>
    void write_vector(const vector<T>& V)
    {
       cout << "The numbers in the vector are: " << endl;
      for(int i=0; i < V.size(); i++)
        cout << V[i] << " ";
    }
    
    int main()
    {
      int input;
      vector<int> V;
      cout << "Enter your numbers to be evaluated: " << endl;
      cin >> input;
      V.push_back(input);
      write_vector(V);
      return 0;
    }
    
    • vince88
      vince88 over 12 years
      In my experience, cin only captures the first token in a string, so anything after a space gets cut off. If you really wanna use cin, either read in each variable separately, or have the user separate the values by a comma and then parse that. Or you can use the argv array in the main method.
    • Benjamin Lindley
      Benjamin Lindley over 12 years
      Did you try using an additional variable? Instead of using n for both the size and the temporary input.
    • R. Martinho Fernandes
      R. Martinho Fernandes over 12 years
      You should explain what's not working here.
    • Roman Byshko
      Roman Byshko over 12 years
      @R.MartinhoFernandes BenjaminLindley I agree with you guys, however I thought the OP spent some time already, and can get the answer. Of course, your approach is much better.
  • Sean
    Sean over 12 years
    Now its stuck in a continuous loop of asking for numbers.
  • Nawaz
    Nawaz over 12 years
    @Sean: No. Enter any non-integer to end the loop!
  • Sean
    Sean over 12 years
    if i ask the user to enter a certain amount of inputs how could i stop it after that many?
  • pezcode
    pezcode over 12 years
    operator void* does not return NULL for EOF, so the while (cin >> input) only aborts for invalid input, but not EOF.
  • greatwolf
    greatwolf over 12 years
    @Sean for(int i = 0; i < inputcount; ++i) { // do your stuff here }
  • Nawaz
    Nawaz over 12 years
    @Sean: Just ask him to enter ANY non-integer to end to the loop. For example, it could be anthing. A, a, jikhjik, 1.29. It should be non-integer. Why don't you experiment, and see how it works?
  • jsinger
    jsinger over 12 years
    Using an istream in a condition, e.g. while (cin >> input) evaluates the stream (or, more precisely in this case, the reference to the stream returned by operator>>) by checking its state, which is made invalid when the stream tries to read in EOF and therefore is evaluated as false.
  • jsinger
    jsinger over 12 years
    Hitting EOF sets both eofbit and failbit. I apparently had some misunderstanding about the evaluation of streams as conditions, though, which your comments have lead me to investigate and clear up, so thanks!
  • R. Martinho Fernandes
    R. Martinho Fernandes over 12 years
    n is initialized with cin >> n.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 12 years
    You forgot to change one n :)
  • Benjamin Lindley
    Benjamin Lindley over 12 years
    @R.MartinhoFernandes: What do you mean? V.size() < n? That's intentional.
  • Sean
    Sean over 12 years
    Works perfect except i would prefer for the program to cin after the ith number instead of i+1. Would i have to use a differrent type of loop for that?
  • Roman Byshko
    Roman Byshko over 12 years
    Shouldn't conditions be switched? If n == 0 you will keep waiting.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 12 years
    I fixed it. You had V.push_back(n).
  • 01d55
    01d55 over 12 years
    By cin after the ith number instead of i+1, did you mean take one fewer input value than this? while (cin >> n && V.size() < i-1) will do that. If you want to take one more instead of one less, i+1 instead. Don't use the ++ or -- operators here, those will change the value of i.
  • Sean
    Sean over 12 years
    i mean by using this say i enter 3 for the amount of numbers to be evaluated. The program wont run until i have entered the fourth number and then it will cout the correct amount being 3. Is there a way to start the program after entering the third number.
  • 01d55
    01d55 over 12 years
    while (V.size() < i && cin >> n)
  • 01d55
    01d55 over 12 years
    No problem. Take a few minutes to look over your questions and accept the answers that you judge most complete - click the check mark outline and it will fill in.
  • voltrevo
    voltrevo over 12 years
    @Nawaz: It works as you say, but how does that work? end is uninitialised; do istream_iterators default construct to some error state which is matched by the other iterator when there is bad input? Seems kinda dodgy to me.
  • Nawaz
    Nawaz over 12 years
    @Mozza314: No. end is not uninitialized, it is class, to the default constructor gets called which initialized it.
  • Daniel Ruf
    Daniel Ruf over 10 years
    please describe what your code does and modify it so it matches the code of the question
  • Aryaman
    Aryaman almost 6 years
    This is exactly what I needed.
  • Marek R
    Marek R over 5 years
    creating an iterator just to fetch single value? Crappy solution. std::copy_n is better in this case.
  • warrior_monk
    warrior_monk over 4 years
    The code is what i need , but it does not input the first number with cin . So if the user enters 2 3 5 6 7 , number starts from 3 in the while loop . How do i fix that ?