i have an assignment to write a C program suing Pointer to count the character or word found in a particular string. i already did it, but i cannot enter the word, its fine with the character. can anybody help me? thx :)

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

int main (int argc, char**argv)
{
    int i, letterCount;
    char LetterToMatch;
    char *c; 
    char string[220];
    printf("Enter a string (220 character max): ");
    
    for (*(c=string)=0; *(c - 1) != '\n';) 
        *c++ = (char) getchar();
    *(c - 1)=0;
    
    printf("Enter any character or words: ");
    
    scanf ("%c", &LetterToMatch);
    
    printf("\nIn this string: \"%s\"\n", string);
    
    for (letterCount=0, c=string; *c; ++c) 
        letterCount += (*c == LetterToMatch) ? 1 : 0;
    
    printf("the character '%c' appears %d time%s.\n", LetterToMatch, letterCount, letterCount == 1 ?"":"s");
    return(0);
}

Hi EarendurRingern.

The problem is that 'LetterToMatch' is not a character array. So whatever you enter doesn't matter after the first letter. That's why your algorithm works whenever you enter just a letter but not an array of letters.

More than that. To fully achieve what you want you should modify the rest of your algorithm as well; that last for loop part.

Comments

char LetterToMatch; is a character so it only fits 1 char, for example a,b,z,d,h. You need something bigger capacity (like a string). And then convert it to char (.c_str())

Comments

I think your control in line 12 might be problematic. Try:

for (c=string; (c==string || *(c-1) != '\n') && c-string < 220;)
    *c++ = (char)getchar();

Or try:

if (fgets(string, 220, stdin)) {
    int last_char_index = strlen(string) - 1;
    if (string[last_char_index] == '\n')
        string[last_char_index] = '\0';
else
    string[0] = '\0';

Of course, yours is shorter....

As far as finding words, the others are right, you need a separate string object to input and store the word to look for, and the function strcmp() will be of interest.

This article has been dead for over six months. Start a new discussion instead.