Question

I need to write a function that will print words that start with specified letter inside a string.. my problem is that once i try to print a words, the function never stop.

Here is the code: (printWords is the functions, printWord is a helper)

#include <stdio.h>
#include <string.h>

typedef char string[50];

void printWord(int *index, string sentence)
{
    while (sentence[*index] != ' ' || sentence[*index] != '\0')
    {
        printf("%c", sentence[*index]);
        *index += 1;
    }   
}

void printWords(char letter, string sentence)
{
    int i = 0, *iPtr = &i;

    if (sentence[0] == letter || sentence[0] == letter + 32)
            printWord(iPtr, sentence);

    for (; sentence[i] != '\0'; i++)
        if ((sentence[i] == ' ' && sentence[i+1] == letter) || (sentence[i] == ' ' && sentence[i+1] == letter + 32))
            printWord(iPtr, sentence);
}

void main()
{
    char ex1_letter;
    int menu;
    string ex1_sentence;

    printf("\n\nPlease enter a string: ");
    gets(ex1_sentence);
    printf("\nPlease enter a letter: ");
    scanf("%c", &ex1_letter);
    printWords(ex1_letter, ex1_sentence);
}

The condition in the loop never seems to happen and i just don't know why.. Any help would be appreciated!

Was it helpful?

Solution

Your main error is using || insted of && in printWord. With || the condition will always be true since the character will always not be either space or the null character.

Some other points:

It's more portable for main to return an int (and have a return 0; at the end).

Use of gets is discouraged as it allows buffer overruns. fgets is more secure, but beware that it leaves the newline character at the end of the string.

Don't do things like letter + 32. Instead, use the functions in ctype.h. In this case, use tolower or toupper.

Instead of passing i as a pointer, just pass it as an int and return the changed value.

Don't use printf and scanf to print/scan a single character. Instead use putchar and getchar.

Use ++i instead of i += 1.

Your typedef just obscures things. If the declaration of (e.g.) printWords is void printWords(char letter, char *sentence) then a C programmer knows what's going on right away without having to know what string is. The typedef really adds nothing.

OTHER TIPS

In your printWord method:

while (sentence[*index] != ' ' || sentence[*index] != '\0')

This conditions will always be true. Change it to &&: print as long it is not a space AND not the end of string, like this:

while (sentence[*index] != ' ' && sentence[*index] != '\0')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top