问题描述
因此,用户需要输入单词数,然后自己输入单词。我应该如何阅读这些单词并将其放入向量中?
#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;
引用这样的向量是语法错误。