String and Array

Hello guys,

i am desperate how to fix this code.
For example i have the

 
  string option;


and then i want to use the string for numbers for an array for example
 
if(SquareMarked[option])

but it is not possible. how can i fix this?
Last edited on
Your post doesn't give enough information to help you, so I'm going to guess here:

If you want to use the string as a sort of "index", one option is to use an std::map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <map>

int main() {
	
	std::map<std::string, int> SquareMarked;
	
	std::string option = "apple";
	
	SquareMarked[option] = 42; // map "apple" to 42
	
	
	if (SquareMarked[option] == 42)
	{
		std::cout << "Did it work?\n";
	}
}

But often this is overkill for a simple options menu, so I am not sure if this is what you want.
Last edited on
Hello Chris26,

As Ganado says post what code you have so what you are asking can be seen in the proper context.


If "SquareMarked" is defined as an array then what is between the []s needs to be a number not a string.

Andy
As the two previous posters have pointed out, there is not enough context to accurately answer your question.

Are you doing a cin of option? If so, then make option an int and it will work as a subscript.
If you're expecting the user to enter a word or phrase, then Gando's suggestion of a std::map is appropriate.

If your intent is something else, please post your code so we can understand the context.
Last edited on
you can convert a string to an integer with std::stoi(stringvar)
so it would just be
SquareMarked[std::stoi(option)] //warning, if option is not valid number in the range of the array's size, this may blow up on you


this is woefully inefficient. you would be better off to store option as an integer, if at all possible, esp if this is done in some sort of loop or could become a bottleneck.

Topic archived. No new replies allowed.