简体   繁体   中英

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

I am currently trying to write a text based RPG. I am working on the user input and how they will choose their actions. I am attempting to take each word from a sentence that the user inputs and put them each separately into an array. That way it can analyze each word and know what the user is attempting to do. I cannot seem to figure out how to go about doing that. I have been looking all around the internet but no one seems to have the same problem as I do. Theres nothing wrong with my code I just cant seem to figure out how.

Here is an example:

#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".
}

I want the user to be able to type any of these commands at any time and then set the variable arrayLength to how many words there are, and then put each word into the array.

How would I do this?

You can use std::istringstream to easily extract the individual words from the input string.

#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';
}

This will wait for the user to enter a complete line before processing it. This is important since std::cin by default treats newline characters as whitespaces during stream operations and will skip them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM