1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

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

Discussion in 'C' started by Martidis, Jan 21, 2010.

  1. Martidis

    Martidis New Member

    Joined:
    Jan 21, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  2. Martidis

    Martidis New Member

    Joined:
    Jan 21, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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]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.
     

Share This Page