Dene Wong
Dene Wong

Reputation: 31

Using a while loop to iterate through a char array received as a parameter in C

I'm still a little new to C, and one hiccup I've been stuck on for the past bit is iterating through a char array received as a parameter. The char array was created as a String literal and passed as an argument. From my understanding this array being received as simply a pointer to the first element in the array; my goal is to loop through each element until reaching the end of the String literal that was passed.

Since I'm required to perform comparisons of each char to char literals inside the loop, I've assigned the value being pointed at in the array, to a char variable that is being used for the comparisons.

Where I'm having trouble is specifying at what point this loop should end.

int main (int argc, char* argv[])
{
    testString("the quick brown fox jumped over the lazy dog");

    return EXIT_SUCCESS;
}

void testString(char line[])
{
    int i = 0;
    int j = 0;
    char ch;
    ch = line[i];

    char charArray[128];

    while (ch != '\0')    // Not sure why this doesn't work
    {   

        if ((ch == '\'' || ch == '-'))
        {
            charArray[j] = ch;
            j++;
        }
        else if (isalpha(ch))
        {
            charArray[j] = ch;
            j++;
        }
        else
        {
             // do nothing
        }

        i++;
        ch = line[i];
    }
}

Thanks in advance for any advice you can offer.

Upvotes: 1

Views: 19064

Answers (1)

dbush
dbush

Reputation: 223917

The exit condition for your loop is working fine.

The only thing missing is that you need to null terminate charArray after the while loop and print it out:

while (ch != '\0')
{
    ...
}
charArray[j] = '\0';
printf("charArray=%s\n",charArray);

Upvotes: 3

Related Questions