Filling array with end of line char

Discussion in 'C++' started by fubz, Jul 23, 2012.

  1. fubz

    fubz New Member

    Joined:
    Jul 23, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hello,
    I have an array that gets filled with a string - however there is no end of line charcter that gets added. So my idea is to first send the array to a function that will fill the whole thing with end of line chars - so when the letters are filled in the next will be end of line be default.

    Code:
    void clearArray(char temp[]) {
    	int i;
    	for(i = 0; i < strlen(temp) - 1; i++) {
    		temp[i] = "\0";
    	}
    }
    
    Here is my function. Although I know the pointer syntax is messed up. I understand pointers I just do not understand when C++ wants/needs a pointer.

    Could someone help me iron out these silly details?
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    if you're wanting to use the array as a null terminated string, then setting the first element to 0, should suffice in "wiping the string". If you're using it as an array of characters, then memset is probably the way to go.

    Code:
    char as_string[20] = { 0 };
    as_string[0] = '\0';
    
    char as_array[20];
    memset(&as_array[0], 0, sizeof(as_array));
    
    In your function, you're dealing with characters and not strings.

    Code:
    temp[i] = '\0';
    If this array is just an array of chars and not a null terminated string, then strlen will probably fail. In that case, pass along the size as another argument.

    Code:
    void clearArray(char *s, int len) {
        int i = 0;
        while(i < len) {
           s[i] = 0;
           ++i;
        }
    }
    
    char as_array[20];
    clearArray(as_array, sizeof(as_array));
    
    Maybe something like that.
     
  3. fubz

    fubz New Member

    Joined:
    Jul 23, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    memset worked great! Thank you so much.
     
  4. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    no worries mate; glad to help. :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice