[英]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
在流操作期间默认将换行符视为空格并将跳过它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.