如何将输入的句子中的单词放入数组中?C++
How to put words from a sentence input into an array? C++
我目前正在尝试编写一个基于文本的RPG。我正在研究用户输入以及他们将如何选择自己的操作。我试图从用户输入的句子中提取每个单词,并将它们分别放入一个数组中。这样它就可以分析每个单词,知道用户想做什么。我似乎不知道该怎么做。我在网上到处找,但似乎没有人和我有同样的问题。我的代码没有什么问题,我只是不知道怎么回事。
这里有一个例子:
#include<iostream>
#include<string>
int main () {
string input [arrayLength];
int arrayLength;
std::cout<<"You are in a mysterious place and you see a creepy man. You don't know where you are. What do you do?"<< std::endl;
//In this case you could either type "run" , "ask man location" , "fight man".
}
我希望用户能够在任何时候键入这些命令中的任何一个,然后将变量arrayLength设置为有多少个单词,然后将每个单词放入数组中。
我该怎么做
您可以使用std::istringstream
轻松地从输入字符串中提取单个单词。
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
int main()
{
std::cout << "You are in a mysterious place and you see a creepy man.n";
std::cout << "You don't know where you are. What do you do?" << std::endl;
// Get input from the user
std::string line;
std::getline(std::cin, line);
// Extract the words
std::istringstream input(line);
std::string word;
std::vector<std::string> words;
while (input >> word)
words.push_back(word);
// Show them just for fun
for (auto&& word : words)
std::cout << word << 'n';
}
这将等待用户输入完整的行,然后再进行处理。这一点很重要,因为默认情况下,std::cin
会在流操作中将换行符视为空白,并跳过它们。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '