Home > Backend Development > C++ > body text

How to Store Multiple User Inputs into a Vector in C ?

Patricia Arquette
Release: 2024-10-30 04:28:28
Original
574 people have browsed it

How to Store Multiple User Inputs into a Vector in C  ?

How to Store User Input (cin) into a Vector

In C , the vector container provides a dynamic array that can be used to store user input. However, when attempting to read user input into a vector using cin, you may encounter issues in counting all the entered numbers.

One common issue is that the code is only reading and pushing a single number into the vector. To resolve this, a loop is required to continually pull in integers from cin. Here's the modified code:

<code class="cpp">int main() {
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;

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

  write_vector(V);
  return 0;
}</code>
Copy after login

This loop continues pulling in integers until cin finds EOF or tries to input a non-integer value. Alternatively, you can use a sentinel value to terminate the loop, preventing the input of that specific value:

<code class="cpp">while ((cin >> input) && input != 9999)
    V.push_back(input);</code>
Copy after login

Once all numbers are stored in the vector, the write_vector function can iterate through and print them for further processing.

The above is the detailed content of How to Store Multiple User Inputs into 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!