Thread: loops with incrementing strings .... ?

  1. #1
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005

    loops with incrementing strings .... ?

    Hi, I'm writing a program with 8 strings (from a to h) and I want to be able to edit elements, copy elements and delete elements from one string to another what not. but the only way I can think of for doing it is to have loads of loops which makes the program very ineloquent and messy.

    it's a very basic chess program. the user says they want to move (for example) from g1 to f1. I have a loop that goes something like

    (wm is the white move [a string with two elements, a letter and number], mp is the moving piece, a, b, ... g, h are strings of 12 elements each)

    if (wm[0]=='a')
    	a[wm[1]-48]=' ';
    I have one of those for a, b, c, d,e, f, g and h, but I want a loop which will do it for me. this equates the moving piece (mp) to the element number you specify in wm[1] in a. as you can see with there being 8 strings, there are a lot of (8 of) these loops. is there a way to do a for loop for string names? If I do it with a letter, it won't work cause the letter is only a sincge character, not a string.

    PS I do hope I'm being clear!!!

  2. #2
    Registered User
    Join Date
    Jan 2005
    To loop from 'a' to 'h', it is pretty safe to have a char variable counter that is initialized to 'a', uses ++ to increment, and loops while it is less than or equal to 'h'.

    This will fix the 'a' in the if statement above to be generic, but the problem is that you cannot do that with variable names. So your a array cannot be switched to the proper variable depending on the loop counter. To fix that you should nest your a through h arrays in another array. For example, have a 2-d array board variable that is [8][8], then the first index will be wm[0]-'a' and your second index will be wm[1]-'0' (you should use '0' instead of 48, it is more clear).

    With that 2-D array you can just do mp = board[wm[0]-'a'][wm[1]-'0'] and you don't even need a loop at all.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. incrementing character strings? pointers? HELP!
    By ominub in forum C Programming
    Replies: 10
    Last Post: 05-02-2009, 09:03 PM
  2. strings and loops
    By steelydan07 in forum C++ Programming
    Replies: 25
    Last Post: 09-18-2006, 12:38 AM
  3. strings and loops...
    By twomers in forum C Programming
    Replies: 5
    Last Post: 12-12-2005, 11:28 AM
  4. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  5. Problems with strings and for loops
    By petedee in forum C Programming
    Replies: 52
    Last Post: 04-02-2004, 03:53 AM