基本上,我想输入一个包含多个单词(未指定长度)的输入行,逐个单词并将每个单词添加到 vector 中。
我可以使用getline并编写一个将其拆分的函数,但想要一种更简洁的方法来读取每个单词,并继续将其添加到 vector 中,直到按Enter键为止。这样直到输入键被按下。谢谢!
vector<string> inp;
while(????)
{
string str;
cin>>str;
inp.push_back(str);
}
我在不使用库的情况下寻找东西,只是按了Enter键时停止输入的某种方式,上述代码的while循环中的某些情况,使得遇到Enter键时,它会爆发并停止接受输入。就像是:while(1)
{
string str;
cin>>str;
// if( character entered =='\0')
//break;
inp.push_back(str);
}
任何帮助,将不胜感激。
最佳答案
拆分字符串的每个单词并将其存储为 vector 的一种好方法是借助std::istringstream
(来自sstream
库):
#include <iostream>
#include <vector>
#include <sstream>
int main(void) {
std::string input;
std::string temp;
std::vector<std::string> words;
std::getline(std::cin, input);
// Using input string stream here
std::istringstream iss(input);
// Pushing each word sep. by space into the vector
while (iss >> temp)
words.push_back(temp);
for(const auto& i : words)
std::cout << i << std::endl;
return 0;
}
作为示例测试案例,您可以看到:$ g++ -o main main.cpp && ./main
Hello world, how are you?
Hello
world,
how
are
you?
关于c++ - 在C++中采用输入行并将行中的单词添加到 vector 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63470603/