std::string words[Maxword] = { "Hello", "World", "Shift", "Green" , "Seven" };
srand(time(NULL));
int iSecret = rand() % 4 1;
std::cout << words[iSecret];
So I have this code which has an array with words in it then picks a random number and that correlates the word how then would I split that word into the letters. Similar to world it would be later compared to letter thats the User would guess
CodePudding user response:
Note sure what you are asking but you can do this to access a character in a string
std::string s = "Word";
std::cout << s[1]; // == 'o'
you can loop
for(int i = 0; i << s.length(); i ){
std::cout << s[i];
}
CodePudding user response:
You have a coupe of options. Both can be handled in the same manner. With your array of std::string, to split the selected word into characters (in a manner where you can provide a second random index and retrieve that character), you could do:
std::cout << words[iSecret] << "\n\n";
for (size_t i = 0; i < words[iSecret].length(); i ) {
std::cout << "words[iSecret][" << i << "]: '" <<
(char)words[iSecret][i] << "'\n";
}
Above, since words[iSecret] is type std::string, you can use the [ ] index operator to select any character at a valid index within words[iSecret]. For all ways of accessing individual characters, you can see std::basic_string.
If you did not need individual character access and simply wanted to loop over each character, you could use a range-based for loop, e.g.
for (const auto& c : words[iSecret])
std::cout << (char)c << '\n';
Example Use/Output
Where running the program with the index operator [ ] for access as shown above, it would produce:
$ ./bin/splitwords-char
Green
words[iSecret][0]: 'G'
words[iSecret][1]: 'r'
words[iSecret][2]: 'e'
words[iSecret][3]: 'e'
words[iSecret][4]: 'n'
or
$ ./bin/splitwords-char
Seven
words[iSecret][0]: 'S'
words[iSecret][1]: 'e'
words[iSecret][2]: 'v'
words[iSecret][3]: 'e'
words[iSecret][4]: 'n'
std::vector As Alternative to array-of-std::string
If you have control over the type for words, then making it std::vector<std::string> words {...} avoids the inflexible limitation of the array-of-std::string. How you access each character would be exactly the same. Whether an element of std::vector<> or an element of the array, the type of the object you are dealing with is still std::string.
In addition to the index operator [ ], you can also use the member function .at() (e.g. words[iSecret].at(i) with the benefit that .at(i) also provides bounds checking on the index provided. See std::basic_string::at
Precedence Problem
You have an error in your use of rand(). % (modulo) has a higher precedence than , so you never access "Hello" (you only access elements 1 to 4). See C Operator Precedence To correct the problem either enclose (4 1) in parenthesis, or simply use rand() % Maxword. That way the values will range from 0 to 4 allowing access to all indexes in words[].
Let me know if you have further questions.
