Home > Backend Development > C++ > body text

How to store multiple user inputs in a vector in C ?

Mary-Kate Olsen
Release: 2024-10-29 04:27:02
Original
402 people have browsed it

How to store multiple user inputs in a vector in C  ?

Understanding User Input Storage in Vectors

In C , a vector is a dynamic array that can efficiently store a collection of elements. When it comes to storing user input in a vector, the process involves using the std::cin stream to read input from the console and pushing it into the vector using the std::vector::push_back() method.

Code Structure

Consider the following code snippet:

<code class="cpp">#include <iostream>
#include <vector>

using namespace std;

template <typename T>
void write_vector(const vector<T>& V)
{
   cout << "The numbers in the vector are : ";
   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: ";
  cin >> input;
  V.push_back(input);
  write_vector(V);
  return 0;
}</code>
Copy after login

Problem Explanation

In this code, the only one number is read from the console and stored in the vector. The write_vector() function then prints the vector, displaying only the first entered number.

Solution

To fix this issue, a loop can be introduced to continuously read inputs from cin until the user enters a non-numeric value, an EOF character, or a specified sentinel value.

<code class="cpp">int main()
{
  int input;
  vector<int> V;

  cout << "Enter your numbers to be evaluated (Enter any non-numeric character to stop): ";
  while (cin >> input)
     V.push_back(input);

  return 0;
}</code>
Copy after login

By using a loop, the code will read multiple inputs and store them in the vector, enabling the write_vector() function to print all the entered numbers.

The above is the detailed content of How to store multiple user inputs in a vector in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!