我应该如何阅读单词并将其放入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;

对于operator<<std::cout没有std::vector<std::string>的过载。您需要自己编写循环:

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

此外,请不要使用using namespace std;。并且std::string的正确标头是<string>,而不是<string.h>

,

您将需要遍历向量并逐个显示单词。 这意味着使用:

for(int i = 0; i < words.size(); i++)
  cout << words[i] << endl;

引用这样的向量是语法错误。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...