所以用户需要先输入字数,然后自己输入字数。我应该如何阅读这些单词并将它们放入向量中?
#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;
}
Run Code Online (Sandbox Code Playgroud)
我试过这个,但是当我运行它时,它给了我一个错误,说“不匹配 'operator<<'”,这与 cout << words; 你们中的任何人都可以解释这个错误吗?
错误不是来自阅读单词,而是来自在这一行打印它们:
cout << words;
Run Code Online (Sandbox Code Playgroud)
没有重载的operator<<forstd::cout需要 a std::vector<std::string>。您需要自己编写循环:
for (auto const & word : words)
std::cout << word << " ";
Run Code Online (Sandbox Code Playgroud)
另外,请不要使用using namespace std;. 正确的标题std::string是<string>,不是<string.h>。