简体   繁体   中英

Terminate string input in a vector loop C++

There is an exercise which dynamically asks for user input and stores in a vector, but I don't know how to end a string input. The book says it is Ctrl + Z but it doesn't work. I am using visual studio 2019 and I know it should work because when I change the variables for integers it does.

int main(void) {
    std::vector<std::string> words;

    for (std::string palabras; std::cin >> palabras;)
        words.push_back(palabras);

    std::string ban = "broccoli";

    for (std::string x : words)
        if (x == ban) std::cout << "Bleep!" << '\n';
        else std::cout << x << '\n';
}

Keep things simple: don't use the return value of std::cin as the for loop condition, unless you're sure what to expect. Here is a simple program that does what you want without using a loop. It would be a good exercise to make that work inside a loop.

#include <iostream>
#include <string>
int main(int argc, char **argv)
{
    std::string lovely_str;
    std::cout << "Enter a string: ";
    std::cin >> lovely_str;
    std::cout << "got: " << lovely_str << "\n";
    return 0;
}

If you insist on using your original program you can use ctrl+d to signal the end of read strings

Take some help of std::istringstream & make life easier (notice comments):

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main(void) {
    // To store the entire line of input
    std::string input;
    // To store the split words
    std::vector<std::string> words;
    // Temporary variable to iterate through
    std::string temp;
    // Constant string to be used
    const std::string ban = "broccoli";

    std::cout << "Enter some words: ";
    std::getline(std::cin, input);

    // Here we go
    std::istringstream iss(input);

    // Separating each words space, e.g. apple <sp> banana => vector apple|banana
    while (iss >> temp)
        words.push_back(temp);

    // Using reference as for-each
    for (auto& i : words)
        if (i == ban) i = "bleep!";

    // Printing the modified vector
    for (auto& i : words) std::cout << i << ' ';

    std::cout << std::endl;

    return 0;
}

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