Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Help with a program in C(searching for a string). (http://www.go4expert.com/forums/help-program-c-searching-string-t20724/)

Martidis 21Jan2010 16:30

Help with a program in C(searching for a string).
 
Hello.

I've been given an assignment to write a program in C that can open a txt file and search for a string. It must then print the lines in which the string was found.

I have the following code so far:

Code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>

main()

{

int i=0;
int line=1;
char s1[8]="Networks";
char s2[8]="networks";
char c,a[8];
FILE *fpt;

if((fpt=fopen("C:\\Keimeno.txt","r"))==NULL)
  printf("\nERROR - cannot open the file ");
else
    while ((c=fgetc(fpt))!=EOF)
    {
        if (c=='\n')
          line=line+1;

        a[i]=c;
        i++;

        if(i==8)
          {
          i=0;
          if((strcmp(a,s2)==1)||(strcmp(a,s1)==1))
          printf("The string was found in line %d...\n\n",line);
          }
      }
system("pause");
}

Although the program detects the line change in the text file, it prints that the string was found in almost every line.
I would really appreciate it if someone helped me with this.

Martidis 21Jan2010 18:48

Re: Help with a program in C(searching for a string).
 
The problem was already solved in another forum. I want to apologize for cross-posting,
but the matter was urgent and I needed an answer fast.

As a sign of responsibility, I will post the solution here:

[IMG]file:///C:/DOCUME%7E1/Raz/LOCALS%7E1/Temp/moz-screenshot-1.png[/IMG]Requinix from the Dev Shed Forums and JackOfAllTrades from Dreamincode forums noted that strcmp returns 0 if the string matches, not 1, which was my mistake.

Also my version of the program doesn't detect the string unless it's at some multiple of 8 characters from the beginning of the line.


All times are GMT +5.5. The time now is 00:05.