1 Replies - 10827 Views - Last Post: 06 April 2009 - 10:19 AM Rate Topic: -----

#1 CaMelToSiSss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 07-March 09

Searching longest word in txt file

Post icon  Posted 06 April 2009 - 08:24 AM

Hello, i need to write a program which will search the longest file in the txt file. And i dont now whats wrong wich my code. When printing its prints some kind of smiles not word.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
	FILE *file;
	char ch, str[500], a=0;
	char file_name[20], long_word[50], temp[50];
	int lenght=0,  b=0,;
	if((file=fopen("file.txt" , "r"))==NULL)
		 printf("Error while opening file\n");
	while (!feof(file))
		  fgets(str, 499, file);
		   if(ch!=' ')
		   if(a > lenght)
		   for (int i=1; i<=lenght; i++)
	printf("Longest word: ");
	for (int i=1; i<=lenght; i++)
	   printf("%c", temp[i]);
	return 0;

maybe you can help me.

This post has been edited by CaMelToSiSss: 06 April 2009 - 08:26 AM

Is This A Good Question/Topic? 0
  • +

Replies To: Searching longest word in txt file

#2 joske  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 43
  • View blog
  • Posts: 297
  • Joined: 04-September 07

Re: Searching longest word in txt file

Posted 06 April 2009 - 10:19 AM

You read a word from the file into the variable str, but you never use that string... I guess you have to copy that to long_word. And I think you don't have to compare if(a > lenght) but if(strlen(str) > strlen(long_word))

You use a for loop to copy a string char by char. After that you should have to add a null character: temp[lenght] = '\0' to give the string an end.
However, much easier is to use the function strncpy() instead of a for loop to copy a string: strncpy(temp, long_word, 50);. Same for printing: you don't have to print a string char by char, you can just use printf("%s\n", temp);.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1