Home > Backend Development > C++ > body text

Why is only the first number being counted when storing user input into a vector?

Patricia Arquette
Release: 2024-10-26 12:01:29
Original
511 people have browsed it

Why is only the first number being counted when storing user input into a vector?

Storing User Input into a Vector: A Comprehensive Guide

In this inquiry, a user is attempting to input multiple numbers into a vector and subsequently count them using a function call. The code provided below presents an issue where only the first number is counted:

<code class="cpp">template <typename T>
void write_vector(const vector<T>&amp; 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;
}</code>
Copy after login

The culprit lies in the fact that currently, only a single integer is being read from the user. To remedy this, a loop is required.

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

This loop continuously retrieves integers from standard input until there is no more input available. The input process concludes when cin detects the end of file (EOF) or encounters a non-integer value.

Alternatively, a sentinel value can be employed, which has the drawback of preventing the user from inputting that particular value. For instance:

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

In this scenario, input is collected until the user enters 9999 (or triggers another condition that renders cin invalid), upon which the loop terminates.

The above is the detailed content of Why is only the first number being counted when storing user input into a vector?. 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!