简体   繁体   中英

Treat a string of words like an array (C++)

Im trying to create a text-based game, im working in a team of other guys and im having a problem creating an item list.

I pretty much want a list of items like an array of words and being able to replace an item with another item by simply pointing to the item like you would pick up an item on your travels in the game.

Is this possible? Every website ive looked at has went into detail about creating an expandanble list of string or memory allocation. All i want to do is have a list of values that I can call from For example I imagined It could work like so.

 item1 = "Lint, dust, sword,axe,gem,Gold key, silver key";
 item2 = "Lint, dust, sword,axe,gem,Gold key, silver key";

cout << "Show:" << item1[3] << " and " << item2[2]
<< "\n";

"Show: Sword and Axe"

instead the outcome is usually "t", as in the 3rd character.

Also the reason I have this idea of working is because Ive worked with Matlab in creating something similar using an array and it worked, maybe thats why I think this should work so simply.

You could use an std::array :

//Declare list of words
std::array<std::string, numwords> words1 = { "Lint", "Dust", "Sword", "Axe", "Gem", "Gold Key", "Silver key" };

Then you can access the words like you did:

words1[3]; //"Axe"
words1[2]; //"Sword"

Note that in C++ indices start from 0, not 1, so index 3 is actually the fourth element in the array.

#include <string>

const std::string list[5] = {"str1","str2","str3","str4","str5"};

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