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:

#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:

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…

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

Edited 4 Years Ago by phummon

cout<<Matrix[ atoi(argv[1]) ]<<"\n";
something i want to say about this line.
argv[1] is a char* type and you converting this to an int. doesn't make sense, and it is not related to the enum you defined

I think you are going to have to make a map of string to enum. 

std::map<std::string, NyNumbers> theMap;
theMap["First"] = First;
// etc...
std::map<std::string, NyNumbers>::iterator pos;
if ( (pos = theMap.find(argv[1])) != theMap.end()){
  // Found!!
  cout << Matrix[pos->second];
  // etc...
}

Edited 4 Years Ago by histrungalot: Format

Thanks histrungalot, this is a really, really cool suggestion. I'll give it a whirl...

Many thanks! This is an awesome forum! -P

This question has already been answered. Start a new discussion instead.