Reputation: 75
I want to get the number of letters of the longest word. If I input something like "hello me" I get 5 but if I write something longer like "league of legends" I get 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;
}
return max;
}
int main(void){
char f[100]; #maybe this is the problem?
int i;
printf("input a string: ");
scanf("%s",f);
i=longest_word(f);
printf("%d",i);
return 0;
}
Upvotes: 1
Views: 529
Reputation: 1
Use getc() in a loop instead of scanf (), as scanf will not consider the input after ' ','\n'...,
Add printf() after scanf() statement., U will come to know.
Upvotes: 0
Reputation: 754570
One of the simplest ways of debugging is to print the data you get to make sure the program got what you think it got.
With scanf()
, the %s
format reads a single 'word', stopping at the first white space. If you printed f
immediately after the call to scanf()
:
printf("Input: <<%s>>\n", f);
you would see that it contains just 'league' so it gives 6 correctly. Strictly, you should check that scanf()
actually got some input before using it:
if (scanf("%99s", f) != 1)
…EOF or error…
You would either need to use fgets()
to read a whole line, or call scanf()
and longest_word()
iteratively to get as far as 'legends' and the answer 7. Note that your code would count a newline (such as is kept at the end of a line by fgets()
) as part of a word. You might want to check the <ctype.h>
header and use the isspace()
macro to test for white space.
Also, as first pointed out by pablo1977 in his answer, you need to initialize max
in longest_word()
.
Upvotes: 5
Reputation: 40145
#include <stdio.h>
int longest_word(const char string[]){
int i;
int max=0;//need initialize
int cont;
i=0;
while(string[i]!='\0'){
for(cont=0;string[i]!=' '&& string[i]!='\0';i++)
cont++;
if (cont>max)
max=cont;
if(string[i]==' ')//Do not increment when string[i]=='\0',,
++i;
}
return max;
}
int main(void){
char f[100];
int i;
printf("input a string: ");
//scanf("%s",f);// a string delimited by white spaces
scanf("%99[^\n]",f);
i=longest_word(f);
printf("%d\n",i);
return 0;
}
Upvotes: 2
Reputation: 4433
The variable max needs to be initialized.
I think this is the problem.
Upvotes: 0