如何将输入的句子中的单词放入数组中?C++

How to put words from a sentence input into an array? C++

本文关键字:数组 C++ 单词放 句子 输入      更新时间:2023-10-16

我目前正在尝试编写一个基于文本的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会在流操作中将换行符视为空白,并跳过它们。