-
longest word problem
Hello,
im having some problems with a menu program for the longest word made of letters only:
Code:
void longest_word(FILE *f,FILE *f1)
{
char data[2000];
int i,len=0,len1=0,k=0;
for(i=0;i<2000;i++)
{
if(data[i]==EOF) break;
data[i]=fgetc(f);
if((data[i]>='a'&&data[i]<='z')||(data[i]>='A'&&data[i]<='Z'))
{ len++;}
else if(len>len1)
{len1=len; k = i-len; len=0;}
}
for(i=k;i<k+len1;i++)
fprintf(f1,"%c",data[i]);
i++;
}
i wrote these words for example:
C@r
pRogram
playground1234
z00
randomstuff@#$%@!@#
cinemacity
the result was:
randomstuff
is there something wrong or im missing something ?
-
You should really work on variable names, comments and indentation to make your code more readable. I'm a bit surprised you got any output since there are numerous problems with your code.
- You only allow up to 2000 characters to be read from the file and pay no attention to the newline characters or spaces that may separate words
- data is an uninitialized array, and you check the contents against EOF before you ever read anything.
- data is an array of chars, but fgetc returns an int (to allow for special values like EOF).
- Is len1 the longest length so far? Why not call it something sensible like max_len?
- What is k? I think it counts non-letters, but then your code in the bottom for loop makes no sense.
- Instead of counting only the letters in each word, you need to break out of the loop if you encounter any non-letters and discard that from your "longest word" search.
- You also need another char array to store the current longest word.
If you know there is going to be one "word" per line in the text file, I would suggest using fgets to read a line at at time, count the characters and discard it if you find anything unsavory. Here's a little pseudo-code to get you going:
Code:
for each line in the file
read line into buf, remove the '\n' from the end and null terminate it
initialize word_len = 0
for i from 0 to the end of buf
if buf[i] is not a letter
break out of for loop
increment word_len
if (word_len > longest_word_len)
copy buf into longest_word
write longest word to file
-
randomstuff is the longest word in your file, with 11 letters compared to 10 for the other things. If you want to say "words that have non-letters stuck to them don't count", then you need to adjust your logic to make sure your words end on a whitespace character, and not just any non-letter.
-
thx a lot for the fast help
im going to try it now