首页 > 解决方案 > 我应该如何阅读单词并将它们放入 C++ 中的向量中?

问题描述

所以用户需要输入单词的数量,然后自己输入单词。我应该如何阅读这些单词并将它们放入向量中?

#include <iostream>
#include <string.h>
#include <vector>

using namespace std;

int main(){
    int n;
    vector<string>words;
    string word;

    cin >> n;
    for (int i = 1; i <= n; i++){
        cin >> word;
        words.push_back(word);
    }
    cout << words;
}

我已经尝试过了,但是当我运行它时,它给了我一个错误,说“不匹配 'operator<<'”,这与 cout << words; 你们中的任何人也可以解释这个错误吗?

标签: c++c++17

解决方案


错误不是来自阅读单词,而是来自在这一行打印它们:

cout << words;

没有operator<<for的重载std::cout需要 a std::vector<std::string>。您需要自己编写循环:

for (auto const & word : words)
  std::cout << word << " ";

另外,请不要使用using namespace std;. 正确的标题std::string<string>,不是<string.h>


推荐阅读