Indexing arrays

Would you mind offering me a little feedback? I thought that I had figured out a clean-cut way of initializing the data for the two multi-dimensional arrays when I read in the data from the file. However, I'm hitting a problem when I try using my variables 'city_from' and 'city_to' to index a block in the array. I think it is because they are strings. I thought that it would work if I had declared the constants at the top, so if the string was 'DEN', than it would reference the constant I had declared at the top of the program and use the integer value I assigned to it to access a particular index in the array. Is there a way that I can bridge the gap? It is looking at the variable as strings, but I need integers to index the array, so is there a way to take the string 'city_from' which says 'DEN' and make it use the constant I declared at the top? If you can help, I would be grateful. It will make my code, as well as the job of initializing values in the arrays, look a lot cleaner. Thanks.


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int SIZE = 8;
const int DEN = 0;
const int LAX = 1;
const int LV = 2;
const int PHX = 3;
const int SFA = 4;
const int SFO = 5;
const int SJC = 6;
const int SLC = 7;

int main()
{
int cost [SIZE][SIZE];
int miles [SIZE][SIZE];
string city_from;
string city_to;
int input;

// Open a file and read in data from the file
char filePath [80];
cout <<"Please enter the path for the file you want to open: " << endl;
cin >> filePath;

ifstream dataFile;
dataFile.open(filePath);

if (dataFile.fail())
{
cout <<"ERROR: Could not open the file" << endl;
system ("PAUSE");
return 0;
}
while (!(dataFile.eof()))
{
dataFile >> city_from;
if (dataFile.good())
{
dataFile >> city_to;
dataFile >> input;
miles[city_from][city_to] = input;
dataFile >> input;
cost [city_from][city_to] = input;
}
}
dataFile.close(); // End of reading in data

No you can not use strings as indexes in arrays.

All of the const you define at the top are int's not strings.

Do you have to use 2d arrays?

You could use a map, partial example follows.

1
2
3
4
5
6
7
map< string, int > cost;
map< string, int > miles;

stringstream ssKey;
ssKey << city_from << ":" << city_to;

cost[ ssKey.str() ] = input;



Topic archived. No new replies allowed.