Thread: Finding a space in an array

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    8

    Finding a space in an array

    Hi everyone, I'm trying to create a loop that finds a space in an array starting from the position 79. I think I have it and it should work but it won't.

    I did a static_cast<int>(' ')l and was given the value 32
    Code:
    for (i = 79; (static_cast<int>(length[i]) == 32); i--)
    counter++;
    Now, the counter gives me the location of the space, which would be I think (79-counter)

    Let me know what you guys think

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    no need for cast..

    if its a character array just check if it equals a space!...

    Code:
    int pos=79;
    while(pos && length[pos--] != ' ');

    as for your code, heres what i think...
    -no need for counter variable, you initialized 'i' outside the for loop anyway so that itself is the position of the space
    -the cast is not needed, just check if its a space ' '
    -in my opinion this is better suited for a while loop, but it doesnt matter really


    your version doesnt work just because you have your for loop condition set to "continue while the character is a space'. instead of 'loop while it IS NOT A SPACE'
    Last edited by rodrigorules; 09-17-2010 at 06:14 PM.

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    8
    Hah, makes perfect sense. I actually changed it into a for statement, a little more convienient for me.

    I'm new to programming so I guess i'm still in the over complicating phase =) Haha thanks a lot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By bennywhere in forum C Programming
    Replies: 16
    Last Post: 10-20-2009, 09:00 PM
  2. warning: excess elements in array initializer
    By redruby147 in forum C Programming
    Replies: 6
    Last Post: 09-30-2009, 06:08 AM
  3. Check char for a space or for end of array?
    By BC2210 in forum C Programming
    Replies: 10
    Last Post: 11-16-2008, 04:14 AM
  4. problems finding the average of an array column
    By mrgeoff in forum C Programming
    Replies: 4
    Last Post: 04-18-2005, 11:49 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM