Home >Backend Development >C++ >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>
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>
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!