c++ - 在C++中采用输入行并将行中的单词添加到 vector 的最佳方法是什么?

标签 c++ string vector

基本上,我想输入一个包含多个单词(未指定长度)的输入行,逐个单词并将每个单词添加到 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/

相关文章:

c++ - printf() 似乎改变了一个变量

android - 非常长的字符串 Eclipse Android

math - 得到一个向量垂直于另一个向量的公式是什么?

c++ - 删除父/子窗口层次结构的最佳方法

c++ - RapidXml:选择一个 first_attribute 值

c++ - 在允许重复子串的情况下查找给定字符串的第 K 个字典顺序子串

c++ - Xalan DLL 丢失

css - 如何在不使用 React Native 中的字符串的情况下将宽度 (100%) 设置为与其父级相同?

java - 不可变字符串有一个很大的优点: the compiler can arrange that stings are shared

matlab - 在 Matlab 中将 3D 矩阵维度作为向量获取