c - Counting the number of letters in the longest word -
c - Counting the number of letters in the longest word -
i want number of letters of longest word. if input "hello me" 5 if write longer "league of legends" 6 instead of 7. why?
#include <stdio.h> int longest_word(const char string[]){ int i; int max; int cont; i=0; while(string[i]!='\0'){ for(cont=0;string[i]!=' '&& string[i]!='\0';i++) cont++; if (cont>max) max=cont; ++i; } homecoming max; } int main(void){ char f[100]; #maybe problem? int i; printf("input string: "); scanf("%s",f); i=longest_word(f); printf("%d",i); homecoming 0; }
one of simplest ways of debugging print info create sure programme got think got.
with scanf(), %s format reads single 'word', stopping @ first white space. if printed f after phone call scanf():
printf("input: <<%s>>\n", f); you see contains 'league' gives 6 correctly. strictly, should check scanf() got input before using it:
if (scanf("%99s", f) != 1) …eof or error… you either need utilize fgets() read whole line, or phone call scanf() , longest_word() iteratively far 'legends' , reply 7. note code count newline (such kept @ end of line fgets()) part of word. might want check <ctype.h> header , utilize isspace() macro test white space.
also, first pointed out pablo1977 in answer, need initialize max in longest_word().
c
Comments
Post a Comment