c++ - 我应该如何阅读单词并将它们放入 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; 你们中的任何人也可以解释这个错误吗?
解决方案
错误不是来自阅读单词,而是来自在这一行打印它们:
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>
。
推荐阅读
- google-cloud-platform - 我可以使用 RSync/Rclone 在生产工作负载中同步 GCS 存储桶吗?
- django - 未使用 Open edX 迁移
- excel - 升级到 365 后复制粘贴停止工作
- conditional-statements - 条件逻辑回归的拟合优度
- firebase - Firebase 查询或报告
- mitmproxy - 是否可以检查 mitm-certificate 是否安装在插件中?
- dictionary - 合并/合并顶级字典
- servicenow - ServiceNow:从 DataTable Widget 访问 sys_id 字段
- mysql - 按当前日期在仪表板中显示值
- python - Pandas 自定义指数衰减