要能用dev运行的代码,一段英文单词由若干单词组成,编写程序提取其中的所有单词。请实现由用户输入英文,利用字符串存储英文,提取后的单词用向量容器存储。 要编写这样
时间: 2024-11-15 11:28:38 浏览: 21
To implement a program that takes user input for an English phrase and extracts all words into a vector container in C++, you can follow these steps:
```cpp
#include <iostream>
#include <sstream> // For string stream to split the input by spaces
#include <vector> // Vector container to store words
std::string input;
std::istringstream iss; // String stream object to process the input
std::vector<std::string> words;
void extract_words() {
std::cout << "Enter an English phrase: ";
std::getline(std::cin, input);
iss.str(input); // Set the string stream's string
if (!iss.fail()) { // If there are no errors reading the input
std::string word;
while (iss >> word) { // Read each word from the input until end of line
words.push_back(word);
}
}
// Print the extracted words for verification
for (const auto& w : words) {
std::cout << w << " ";
}
}
int main() {
extract_words();
return 0;
}
```
In this code, we use `std::getline` to get the user input as a single string, then create an `std::istringstream` to split it into individual words using `std::istringstream::operator>>(word)`. Each word is added to the `words` vector. After extraction, the program prints the words.
阅读全文