4.一段英文单词由若干单词组成,编写程序提取其中的所有单词。请实现由用户输入英文,利用字符串存储英文,提取后的单词用向量容器存储。
时间: 2024-11-15 18:29:06 浏览: 40
要编写这样的程序,你可以使用C++标准库中的`std::istringstream`和`std::vector<std::string>`。首先,让用户输入一个英文句子,然后将这个句子分割成单词。以下是简单的步骤:
```cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
// 函数用于从输入流中提取单词并添加到向量中
void extract_words(const std::string& input, std::vector<std::string>& word_vector) {
std::istringstream iss(input);
std::string word;
// 使用空格作为分隔符
while (iss >> word) {
word_vector.push_back(word);
}
}
int main() {
std::cout << "请输入英文句子:" << std::endl;
std::string input;
std::getline(std::cin, input); // 读取整行输入
std::vector<std::string> words;
extract_words(input, words);
// 打印提取出的单词
for (const auto& w : words) {
std::cout << w << " ";
}
// 提取出的单词已存储在words向量中
阅读全文
相关推荐

















