Crosley33 Crosley33 - 3 months ago 15
C++ Question

cin strings into a Vector (c++)

So I am basically trying to the same thing 2 different ways.
The while loop is perfect but it stores the "." in the vector which I do not want to do but its the only way to exit the loop.

The second with the copy function; I don't know how to break or exit.
I believe this would help others.

Could I have some pointers in my investigation?
Thank you

while (keyinput != ".")
{
cin >> keyinput;
words.push_back(keyinput);
}

copy(std::istream_iterator<string>(cin),
std::istream_iterator<string>(),
back_inserter(words));

Answer

Use a do...while loop:

do {
    if (!(cin >> keyinput)) {
        // error handling...
        break;
    }
    if (keyinput == ".") break;
    words.push_back(keyinput);
}
while (true);
Comments