Thread: Accessing an array index with a string?

  1. #1
    Registered User
    Join Date
    Nov 2008

    Accessing an array index with a string?

    Is it possible to access an array index with a string? For example

    string week[7];
    week["Monday"] = "some value";

    I'm trying to read in a Java properties file and want to be able to access each property by its name instead of an index number. I can't use map.h since that's tied to gnu c++.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    That would be a map. (I have no idea what you mean by "map.h is tied to gnu c++" since (1) it's <map> not <map.h> and (2) it most certainly is not tied to GNU.)

  3. #3
    Registered User
    Join Date
    Nov 2008
    Oh... looks like you're right. I thought the map functionality was tied to gnu. Maybe that's for C? Any I now have

    #include <string>
    #include <iostream>
    #include <fstream>
    #include <map>
    using namespace std;
    typedef map<const string, const string> Properties;
    int main()
        string propsLoc = "";
        Properties props;
        char s[256];
        string temp;
        /* Read properties file into props */
        ifstream ifs( propsLoc.c_str() );    
          temp = s;
          props.insert(pair<const string, const string>(temp.substr(0,temp.find('=')),temp.substr(temp.find('=')+1)));
    But the insert function is giving me an error. Does this code look correct?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Use std::make_pair instead, e.g.,
    props.insert(make_pair(temp.substr(0, temp.find('=')), temp.substr(temp.find('=') + 1)));
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. C/C++ String Problem.
    By Jaken Veina in forum C++ Programming
    Replies: 7
    Last Post: 07-09-2005, 10:11 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM