簡體   English   中英

獲取輸入行並將行中的單詞添加到 C++ 中的向量的最佳方法是什么?

[英]What is the best way to take an input line and add the words in the line to a vector in C++?

基本上我想輸入一個包含多個單詞(未指定長度)的行,一個單詞一個單詞並將每個單詞添加到一個向量中。 我可以使用 getline 並編寫一個 function 來拆分它,但想要一種更簡潔的方式來讀取每個單詞並繼續將其添加到向量中,直到按下 Enter 鍵。 像這樣直到按下回車鍵。 謝謝!

vector<string> inp;
    while(????)
    {
    string str;
    cin>>str;

    inp.push_back(str);
    }

我正在尋找不使用庫的東西,只是在按下回車鍵時停止接受輸入的某種方式,上面代碼中 while 循環中的某些條件使得當遇到回車鍵時,它會中斷並停止接受輸入。 就像是:

while(1)
{
  string str;
  cin>>str;
  // if( character entered =='\0')
        //break;
  inp.push_back(str);
}

任何幫助,將不勝感激。

什么是最好的是不可能回答的; 這取決於你如何衡量善良,並且很大程度上是品味和個人喜好的問題。
例如,有些人喜歡編寫顯式循環,而其他人則盡可能避免使用它們。

一種不使用顯式循環的方法是使用std::copystd::istringstream

std::vector<std::string> words;
std::string line;
if (std::getline(std::cin, line))
{
    std::istringstream is(line);
    std::copy(std::istream_iterator<std::string>(is),
              std::istream_iterator<std::string>(),
              std::back_inserter(words));
}

拆分字符串的每個單詞並將它們存儲到向量中的一種好方法是借助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?

以下代碼與@Rohan Bari 的答案幾乎相同,但我發布是因為拆分字符串有所不同。

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

int main(void)
{
    std::string input;
    std::getline(std::cin, input);
    std::stringstream ss(input);
    auto words = std::vector<std::string>(std::istream_iterator<std::string>(ss), {});  // difference

    for (const std::string& s : words)
        std::cout << s << std::endl;

    return 0;
}

暫無
暫無

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

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