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>
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>
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!