Using a string/enum to access int Matrix[X] ?

Hola code gurus,

I’m wondering if there’s a way to use a string to access a specific item in a matrix of int[X].

I have a program which uses enums as iterators to reference a large amount of data. To select an item in the matrix, the user will enter a string, which is also an enum, which also must serve as an iterator for something in the matrix. Here is a toybox example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

enum NyNumbers { First, Second, Third, Forth, LAST_VALUE };

int main(int argc, char* argv[]) {

  int Matrix[LAST_VALUE] = { 1, 3, 7, 12 };

  cout<<"Matrix[ atoi("<<argv[1]<<") ]:  ";
  cout<<Matrix[ atoi(argv[1]) ]<<"\n";

  return 0;
}

The idea is the user executes the program by typing “./RUN First” to print out the first element in the MyNumbers array, “./RUN Second” to access the second, and so on. I can’t use static numbers for the iterator. (i.e., “./RUN 1”) I must reference by enum/string.

When run, the output of this problem is thus:
1
2
3
user@debian$ ./RUN Second
Matrix[ atoi(Second) ]:  1
user@debian$

BTW, if I change line 12 to this…
cout<<Matrix[ argv[1] ]<<"\n";
…the error message is this…
1
2
3
4
5
6
user@debian$ make
g++ -g -Wall -ansi -pg -D_DEBUG_   Main.cpp -o exe
Main.cpp: In function `int main(int, char**)':
Main.cpp:12: error: invalid types `int[4][char*]' for array subscript
make: *** [exe] Error 1
user@debian$

…which isn’t unexpected. Any idea how to imput the enum as argv[1]?

Many thanks!
-P
Last edited on
atoi converts strings such as "6121" to numbers such as 6121. It does not convert strings such as "Second" to numbers such as 1 or 2.
Last edited on
You need to include stdlib.h.
Don't enums already mean the number but just represented with the name given in the enum definition?
Yes, but C++ is not reflective so the names no longer exist at runtime when you would want them for this scenario.
You need to convert your string to a number.

Here are examples of doing similar things:

Idiot-proof YES or NO:
http://www.cplusplus.com/forum/beginner/18518/#msg94815

Switch on a string (Convert Month Name to Index)
http://www.cplusplus.com/forum/general/11460/#msg54095 (scroll down to the second example)
Topic archived. No new replies allowed.