std::cin >> a
will skip all whitespace and will only put non-whitespace characters into the string. This means, among other things, that a
will never be empty, even if you just press enter. So even a check for a.empty()
would do you no good here. The loop will continue until something is wrong with your I/O environment (i.e. practically never) or you run out of memory because the vector gets too large, in which case the loop is exited via an exception.
What you need to do is to call std::getline
instead. That function reads a whole line of input and stops after a newline, rather than completely disregarding the newline. Then you can check for empty()
to see if nothing was entered. Here is an example:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string a;
std::vector<std::string> test;
while (std::getline(std::cin, a) && !a.empty()) {
test.push_back(a);
}
for (auto const& s : test) {
std::cout << s << '\n';
}
}
I've also simplified the code and taken the liberty to show you that using namespace std;
and system("pause")
are bad ideas.