Home > Backend Development > C++ > body text

How can I store multiple user inputs in a vector using cin in C ?

Mary-Kate Olsen
Release: 2024-10-28 18:02:02
Original
746 people have browsed it

How can I store multiple user inputs in a vector using cin in C  ?

Storing User Input in a Vector using cin

In C , a vector is a dynamic array that can store elements of the same type. To store user input in a vector, you can use the cin stream object. However, it's important to consider the limitations of the code provided.

Understanding the Provided Code

The given code attempts to read numbers from the user and store them in a vector. However, it only captures the first number entered. To resolve this issue, a loop is necessary to continuously accept multiple integers.

Solution

The modified version of the code below:

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

  // Use a loop to read multiple integers from cin
  while (cin >> input)
    V.push_back(input);

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

By utilizing the loop, this updated code reads numbers until the user presses Ctrl D (Linux/Mac) or Ctrl Z (Windows). Each entered number is added to the vector.

Additional Considerations

An alternative approach involves using a sentinel value. This allows for a specific value to signal the end of input, as shown below:

<code class="cpp">int main() {
  int input;
  vector<int> V;
  cout << "Enter numbers (enter -1 to stop): " << endl;

  // Use a sentinel value to terminate input
  while (cin >> input && input != -1)
    V.push_back(input);

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

In this scenario, entering "-1" will stop user input and terminate the loop.

The above is the detailed content of How can I store multiple user inputs in a vector using cin 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!