[英]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.
这本书说它是Ctrl + Z但它不起作用。 I am using visual studio 2019 and I know it should work because when I change the variables for integers it does.
我正在使用 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';
}
Keep things simple: don't use the return value of std::cin
as the for loop condition, unless you're sure what to expect.保持简单:不要使用
std::cin
的返回值作为 for 循环条件,除非您确定会发生什么。 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如果您坚持使用您的原始程序,您可以使用
ctrl+d
来表示读取字符串的结束
Take some help of std::istringstream
& make life easier (notice comments):借助
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.