The while loop will go on until cin >> n
fails. It doesn't fail when you press enter. Enter is treated like any other whitespace character and will be skipped by default when doing formatted reading using operator>>
.
You could read complete lines and extract data from those instead. If the user enters a blank line, you break out of the loop.
#include <iostream> // include the correct headers, not bits/stdc++.h
#include <sstream>
#include <string>
#include <vector>
// don't do: using namespace std;
int main() {
std::vector<int> array;
for(std::string line; std::getline(std::cin, line);) {
if(line.empty()) break; // the user didn't enter anything, break out
// put the line in an istringsstream for extraction
std::istringstream is(line);
int n;
while(is >> n) { // extract from the istringstream
array.push_back(n);
}
// if you want to break out of the loop if the user entered
// something that couldn't be extracted:
if(not is.eof()) { // if all was extracted, eof() will be true
is.clear(); // clear the error state from the failed extraction
std::getline(is, line); // read out the rest of the line
std::cout << "could not extract an int from \"" << line << "\".\n";
break;
}
}
// print the result
for(auto i: array) {
std::cout << i << ' ';
}
std::cout << '\n';
}
If you only want exactly one line of data, replace the for
loop with
if(std::string line; std::getline(std::cin, line)) {
and adjust the break
s accordingly (since there's no loop to break out of).