0

I have function, which should count how many characters have the longest word, but it counts wrong.

For example, if I enter two words when first one is shorter than second one: "my name" program shows me that the longest word has 2 chars. But when i enter "name my" it shows that the result is 4. why is that ?

void max_chars(ListNodePtr sPtr)
{
    int i = 0;
    int max = 0;

    while (sPtr->next != NULL) {
        if (isalpha(sPtr->data)) {
            i++;
        } else {
            if (i > max) {
                max = i;
            }
            i = 0;
        }
        sPtr = sPtr->next;
    }

    printf(" \n The Longest word have : %d chars \n", max);
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Lukas M.
  • 163
  • 1
  • 2
  • 13
  • Is `sPtr=sPtr->next` incrementing something? I mention it because you call it twice per loop. One in the while statement, once in the body of the loop. If it is incrementing some pointer, then you go two by two characters. Try printing the currently evaluated character to see what's happening. – Jean Mar 17 '13 at 22:07
  • Instead of use NULL use '\0' (standard) – Mitro Mar 17 '13 at 22:21
  • And look this http://stackoverflow.com/questions/15340343/strings-gets-and-do-while – Mitro Mar 17 '13 at 22:22

2 Answers2

2

In my name when you reach the node e you break the loop since the next is null and so the max is not updated.
You should update max outside of the loop as well or change the condition of the loop

Cratylus
  • 52,998
  • 69
  • 209
  • 339
0
void max_chars(ListNodePtr sPtr)
{
    int i = 0;
    int imax = 0;

    for( ;sPtr; sPtr = sPtr->next;) {
        if (isalpha(sPtr->data)) { if(++i > imax) imax=i; }
        else { i = 0;  }
    }

    printf(" \n The Longest word have : %d chars \n", imax);
}
wildplasser
  • 43,142
  • 8
  • 66
  • 109