简体   繁体   中英

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));

You just need to re-order things so the check is done before the push_back

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

Let's analyze your code a line at a time:

Check for a "." in the input

while (keyinput != ".") {

Get next input

    cin >> keyinput;

Add input the the vector

    words.push_back(keyinput);
}

Note that when the user finally enters a "." , it will be added to the vector.

In general, any code which affects the condition of a while loop should be immediately before the while loop checks the condition without any lines of code in between. There are two ways to accomplish this:

  1. Get input immediately before the while loop and at the end of the while loop.

  2. Use a do .. while loop instead.

Since you don't want to store . into vector. You have to insert the value just before you are taking input inside while loop.

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

Use a do...while loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM