Search line containing exact word...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kristapins
    New Member
    • Nov 2007
    • 6

    Search line containing exact word...

    Hello!
    Can anyone help me... I have *.txt file containing lines like...

    100 0 0 7 high UNLOCKED CRITICAL Door open in site CLEARED
    100 11 0 7 low UNLOCKED CRITICAL Door Open CLEARED
    100 12 0 0 high UNLOCKED CRITICAL Power suppy CLEARED
    100 12 0 1 high UNLOCKED CRITICAL Fire CLEARED
    100 12 0 2 low UNLOCKED CRITICAL Temperature CLEARED

    Code is...

    #include "stdafx.h"
    #include <cstdlib>
    #include <iostream>

    using namespace std;

    int _tmain(int argc, _TCHAR* argv[])
    {
    //norādam failu, kuru nolasam
    FILE *statistic = fopen ("C:\\Tele2\\EN VAS\\Confenvarc 1-0512.txt", "r");
    //izveidojam output failu, kas tiek papildināts
    FILE *envas = fopen ("C:\\Tele2\\EN VAS\\RC1.txt", "a");
    //lasam failu
    while (!feof(statisti c))
    {
    char key[4];
    int trash[3];
    char string[10];
    char line[200];
    fgets (line,200,stati stic);
    sscanf (line,"%d %d %d %d %s", &trash[0], &trash[1], &trash[2], &trash[3], &key[0]);
    if( key=="high" )
    {
    printf("%s",lin e);
    // fprintf(envas," %s",line);
    }
    }
    fclose (statistic);
    fclose (envas);
    system("PAUSE") ;
    return EXIT_SUCCESS;
    }

    As you see I'm trying to find lines containing word "high", but it returns empty screen... If there is some error in script...???
  • jabbah
    New Member
    • Nov 2007
    • 63

    #2
    I'm afraid you have multiple problems here

    trash can hold 3 int's (i.e. from index 0 to index 2) but you try to write 4 int's into it

    key can hold 4 char's but I think sscanf would add a \0 when reading a string %s so to hold the string "high" it should be at least 5 chars long. plus if you ever happen to read a file that contains a string that is longer than 4 char's you would still write beyond the end of key.


    also == will not make a literal comparision of strings. there is a function called strcmp to do that.

    I don't want to be rude, but maybe you should start with some c++ tutorial for reading from a file?

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by Kristapins
      key=="high"
      For openers, you can't compare C-strings this way. C strings are char arrays and the name of an array is the address of element 0. You are comparing the addresses of the two strings. Since the strings are in different locations, the addresses will always be different. You need to use a string compare function.

      Next, you should be using the TCHAR mappings, and you are not. This code can't be used with Unicode. All Windows code is supposed to use these TCHAR mappings.

      Comment

      Working...