0

I was trying to traverse and output the vector, but there is nothing happened other than asking me for input.

int main() {
    string a;

    vector<string> test;
    while (std::cin>>a) {
        test.push_back(a);
    }
    for (vector<string>::iterator i= test.begin(); i!= test.end(); ++i) {
        std::cout << *i << std::endl;
    }
    system("pause");
    return 0;
}
Joey LU
  • 77
  • 1
  • 12

1 Answers1

1

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.

Community
  • 1
  • 1
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • Thank you so much. One more question since the loop stops after a newline, there seems no necessary to add empty(). – Joey LU May 01 '17 at 11:14
  • @JoeyLU: If you remove the `empty()` check, then the loop will once again be endless, because `std::getline` does not set `std::cin` to a fail state just because the entered string is empty. – Christian Hackl May 01 '17 at 11:16
  • Thanks for your further explanation – Joey LU May 01 '17 at 11:33
  • @Joey LU: if you like the answer, mark it as accepted answer. Moreover, you can vote up for it by clicking the up arrow at the beginning of the answer if you would like to do. See [here](http://stackoverflow.com/tour). – Shadi May 02 '17 at 00:21