Thread: question regarding accessing variable values

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    8

    question regarding accessing variable values

    Hey guys,

    I was wondering if anybody knew if it was possible to initialize the value of a variable to a few letters plus a value that itself is stored in a different variable.

    For example (the exact example I'm trying to do!), lets say that we're trying to keep track of the location of a character on an x and y grid. Variables currentx and currenty represent the characters current location, and I want to save, to an array, the value room(currentx)(currenty).. so assuming the character was on spot 13, I would want to save room13 to the array.

    I hope I managed to explain that in a way that made sense.

    Thank you for your time! Any thoughts are appreciated!

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    I believe you're asking about creating a string, but I'm not certain. If not, this answer probably won't be useful:
    Code:
    char location[64];
    int x = 1, y = 3;
    sprintf(location, "room%d%d", x, y);
    sprintf() is just like printf() except that instead of writing to the standard output, it creates a string and writes that to the first argument. There's danger involved with sprintf(): it doesn't know how large your array is so it's possible to have an overflow, which is bad. In your code you know that x and y will never be larger than a particular value, so sprintf() can be used safely. That is, if your grid is 10x10, you know that the longest string you can make is 9 characters: room1010 plus one more character for the string terminator.

    If you use sprintf() just remember that it is dangerous. There is a replacement called snprintf() that is safe, but it's not as widely available as sprintf().

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    8
    That's exactly what I was trying to do.

    Thanks so much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. vector : accessing values
    By rahulsk1947 in forum C++ Programming
    Replies: 1
    Last Post: 06-01-2009, 09:26 PM
  2. newb question: dynamic variable names
    By Dash_Riprock in forum C++ Programming
    Replies: 6
    Last Post: 07-17-2006, 10:48 AM
  3. Global variable question
    By csisz3r in forum C Programming
    Replies: 10
    Last Post: 09-19-2005, 07:19 AM
  4. Accessing Void Function Question
    By liquidspaces in forum C++ Programming
    Replies: 2
    Last Post: 03-27-2003, 02:06 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM