The question may seem stupid, but I don’t understand why when compiling this code in visual studio, when you fill in the vector and press enter, the numbers contained in the vector are not displayed, the code seems to look correct, maybe this is due to some environment settings, tell me Please.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int x;
vector<int> my_vector;
while (cin >> x) {
my_vector.push_back(x);
}
for (auto p : my_vector) {
cout << p << " ";
}
return 0;
}
I tried compiling this code in Visual Studio 2022 and Visual Studio 2019
2
Answers
Well, you also have to go out of the loop or programmatically, break the loop.
This is the fixed version of the code
Here is another solution.
But, when entering a string that starts with a number and ends with other characters, the number part will be push_back.
Eg. cin: 1qwe123. Get: 1, ignore qwe123.