How to cin values into a vector

C++FunctionTemplatesVectorCin

C++ Problem Overview


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;
}

C++ Solutions


Solution 1 - C++

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 - C++

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 - C++

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 - C++

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 - C++

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;
    }
}

Solution 6 - C++

One-liner to read a fixed amount of numbers into a vector (C++11):

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <cstddef>

int main()
{
    const std::size_t LIMIT{5};
    std::vector<int> collection;

    std::generate_n(std::back_inserter(collection), LIMIT,
        []()
        {
            return *(std::istream_iterator<int>(std::cin));
        }
    );

    return 0;
}

Solution 7 - C++

If you know the size use this

No temporary variable used just to store user input

int main()
{
    cout << "Hello World!\n"; 
	int n;//input size
	cin >> n;
	vector<int>a(n);
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}

//to verify output user input printed below

	for (auto x : a) {
		cout << x << " ";
	}
	return 0;
}

Solution 8 - C++

You need a second integer.

int i,n;
vector<int> V;
cout << "Enter the amount of numbers you want to evaluate: ";
cin >> i;
cout << "Enter your numbers to be evaluated: " << endl;
while (V.size() < i && cin >> n){
  V.push_back(n);
}
write_vector(V);
return 0;

Solution 9 - C++

You probably want to read in more numbers, not only one. For this, you need a loop

int main()
{
  int input = 0;
  while(input != -1){
    vector<int> V;
    cout << "Enter your numbers to be evaluated: " << endl;
    cin >> input;
    V.push_back(input);
    write_vector(V);
  }
  return 0;
}

Note, with this version, it is not possible to add the number -1 as it is the "end signal". Type numbers as long as you like, it will be aborted when you type -1.

Solution 10 - C++

cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as

int input;
cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
while(input != 10000) {
    cin >> input;
   V.push_back(input);
}
write_vector(V);

Solution 11 - C++

You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.

int main() {
        int sizz,input;
    	std::vector<int> vc1;
    	
    	cout<< "How many Numbers you want to enter : ";
    	cin >> sizz;
    	cout << "Input Data : " << endl;
    	for (int i = 0; i < sizz; i++) {//for taking input form the user
    		cin >> input;
    		vc1.push_back(input);
    	}
    	cout << "print data of vector : " << endl;
    	for (int i = 0; i < sizz; i++) {
    		cout << vc1[i] << endl;
    	}
     }

Solution 12 - C++

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
	vector<string>V;
	int num;
	cin>>num;
	string input;
	while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
	//cin>>input;
   V.push_back(input);
   num--;
   if(num==0)
   {
   vector<string>::iterator it;
    for(it=V.begin();it!=V.end();it++)
        cout<<*it<<endl;
   };

}
return 0;
   
};

Solution 13 - C++

#include<iostream>
#include<vector>
#include<sstream>
using namespace std;

int main()
{
	vector<string> v;
	string line,t;
	getline(cin,line);
	istringstream iss(line);
	while(iss>>t)
		v.push_back(t);

	vector<string>::iterator it;
	for(it=v.begin();it!=v.end();it++)
		cout<<*it<<endl;
	return 0;
}

Solution 14 - C++

In this case your while loop will look like

int i = 0;
int a = 0;
while (i < n){
  cin >> a;
  V.push_back(a);
  ++i;
}

Solution 15 - C++

The initial size() of V will be 0, while int n contains any random value because you don't initialize it.

V.size() < n is probably false.

Silly me missed the "Enter the amount of numbers you want to evaluate: "

If you enter a n that's smaller than V.size() at that time, the loop will terminate.

Solution 16 - C++

Just add another variable.

int temp;
while (cin >> temp && V.size() < n){
    V.push_back(temp);
}

Solution 17 - C++

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

int main()
{
int x,n;
cin>>x;
vector<int> v;

cout<<"Enter numbers:\n";

for(int i=0;i<x;i++)
 {
  cin>>n;
  v.push_back(n);
 }


//displaying vector contents

 for(int p : v)
 cout<<p<<" ";
}

A simple way to take input in vector.

Solution 18 - C++

These were two methods I tried. Both are fine to use.

int main() {
       
        int size,temp;
        cin>>size;
        vector<int> ar(size);
    //method 1 
      for(auto i=0;i<size;i++)
          {   cin>>temp;
              ar.insert(ar.begin()+i,temp);
          }
          for (auto i:ar) 
            cout <<i<<" "; 
            
     //method 2
     for(int i=0;i<size;i++)
     {
     	cin>>ar[i];
     }
     
     for (auto i:ar) 
            cout <<i<<" "; 
    	return 0;
    }

Solution 19 - C++

would be easier if you specify the size of vector by taking an input :

int main()
{
  int input,n;
  vector<int> V;
  cout<<"Enter the number of inputs: ";
  cin>>n;
  cout << "Enter your numbers to be evaluated: " << endl;
  for(int i=0;i<n;i++){
  cin >> input;
  V.push_back(input);
  }
  write_vector(V);
  return 0;
}

Solution 20 - C++

I ran into a similar problem and this is how I did it. Using &modifying your code appropriately:

   int main()
   {
   int input;
   vector<int> V;
   cout << "Enter your numbers to be evaluated: " 
   << '\n' << "type "done" & keyboard Enter to stop entry" 
   <<   '\n';
   while ( (cin >> input) && input != "done") {
   V.push_back(input);
    }
   write_vector(V);
   return 0;
  }
   

Solution 21 - C++

cout << "do you like to enter the sem 2 score "<<endl;
cin >> sem2;

if (sem2 == 'Y' || sem2 == 'y')
{
	cout << "enter your subject count ";
	cin >> subjectcount;
	cout << " enter your scores :";
	for (int i = 0; i < subjectcount; i++)
	{
		double  ip;
		cout << (i+1) << " st score ";
		cin >> ip;
		sem2score.push_back(ip);
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeanView Question on Stackoverflow
Solution 1 - C++jsingerView Answer on Stackoverflow
Solution 2 - C++NawazView Answer on Stackoverflow
Solution 3 - C++Jon PurdyView Answer on Stackoverflow
Solution 4 - C++H_meirView Answer on Stackoverflow
Solution 5 - C++阿尔曼View Answer on Stackoverflow
Solution 6 - C++Wojciech MigdaView Answer on Stackoverflow
Solution 7 - C++Amit SharmaView Answer on Stackoverflow
Solution 8 - C++01d55View Answer on Stackoverflow
Solution 9 - C++poitroaeView Answer on Stackoverflow
Solution 10 - C++johnathanView Answer on Stackoverflow
Solution 11 - C++Arslan Ahmad khanView Answer on Stackoverflow
Solution 12 - C++shiva MirjapurView Answer on Stackoverflow
Solution 13 - C++shunbenbenView Answer on Stackoverflow
Solution 14 - C++Roman ByshkoView Answer on Stackoverflow
Solution 15 - C++Thom WiggersView Answer on Stackoverflow
Solution 16 - C++Benjamin LindleyView Answer on Stackoverflow
Solution 17 - C++RohitView Answer on Stackoverflow
Solution 18 - C++r.saiprasadView Answer on Stackoverflow
Solution 19 - C++Vivek Kumar SinghView Answer on Stackoverflow
Solution 20 - C++Mallam AwalView Answer on Stackoverflow
Solution 21 - C++RivendharanView Answer on Stackoverflow