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