簡體   English   中英

在向量循環中終止字符串輸入 C++

[英]Terminate string input in a vector loop C++

有一個練習動態地詢問用戶輸入並存儲在向量中,但我不知道如何結束字符串輸入。 這本書說它是Ctrl + Z但它不起作用。 我正在使用 Visual Studio 2019,我知道它應該可以工作,因為當我更改整數的變量時,它可以工作。

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';
}

保持簡單:不要使用std::cin的返回值作為 for 循環條件,除非您確定會發生什么。 這是一個簡單的程序,它可以在使用循環的情況下執行您想要的操作。 循環中進行這項工作將是一個很好的練習。

#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;
}

如果您堅持使用您的原始程序,您可以使用ctrl+d來表示讀取字符串的結束

借助std::istringstream並讓生活更輕松(注意評論):

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM