Trouble while trying to find a specific word

hey. im trying to find a word in a txt file and if it is found count 11 lines after it, then save the word in a var and the destination in a var.

 
cant even start a code :P
drop the entire text file to a single big string. do the string.find on it for your word. Find 11 end of line strings/chars (depends on OS here). do a substring to pull your word from the find into a variable. save the destination (?character? ?location? ?pointer? or ???) into another variable.

Be sure to account for word not found and there not being 11 lines after it and maybe consider what you do if you find it again.

give it a try. surely you can write an empty main program, and add a couple of strings to it. do you know how to open a text file and read it?
Last edited on
Using the standard regular expressions library http://en.cppreference.com/w/cpp/regex would make life easier.
To extract just one line from a file, there is no need to read the entire contents of the file into memory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>
#include <fstream>
#include <regex>

// return true if the line contains the word
// assumes that the word contains only alphanumeric characters
bool contains_word( const std::string& line, const std::string& word )
{
    // (?:^|\\s) - either beginning of string or a non-alphanumeric character
    // followed by the word we are looking for (ignore case)
    // followed by (?:$|\\s+) - either end of string or a nonalpha-numeric character
    std::regex word_re( "(?:^|\\W)" + word + "(?:$|\\W+)", std::regex_constants::icase ) ;
    return std::regex_search( line, word_re ) ;
}

std::istream& get_nth_line( std::istream& stm, std::string& line, std::streamsize n )
{
    while( n-- > 1 ) std::getline( stm, line ) ; // skip n-1 lines
    std::getline( stm, line ) ;
    return stm ;
}

int main()
{
    const std::string word = "abracadabra" ; // the word we are looking for
    const std::streamsize n = 11 ; // #lines after the line containing the word

    std::ifstream file( "my_file.txt" ) ; // open the file for input

    if( file.is_open() )
    {
        // keep reading lines one by one till we get to the line containing the word
        std::string line ;
        while( std::getline( file, line ) && contains_word( line, word ) ) ;

        if(file) // the stream is not in a failed state; we found the word
        {
            // try to read the nth line from the current position
            if( get_nth_line( file, line, n ) ) std::cout << line << '\n' ;
            else std::cerr << "*** error: reached end of file\n" ;
        }

        else std::cerr << "*** error: the word was not found\n" ;
    }
    else std::cerr << "*** error: could not open file for input\n" ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;

//======================================================================

string filter( string s )                                       // filter to lower case, with only alphabet and numbers
{
   string result = "";
   for ( char c : s ) if ( isalnum( c ) ) result += tolower( c );
   return result;
}

//======================================================================

bool getNthLine( istream &in, int N, string &line )
{
   for ( int i = 0; i < N; i++ ) getline( in, line );           // read N lines, overwriting line each time
   if ( in ) return true;                                       // successfully read; line returned as argument
   line = "";                                                   // returns false (and empty string) if unsuccessful
   return false;
}

//======================================================================

bool findWord( istream &in, string word )
{
   word = filter( word );                                       // word in common (here, lower-case) form
   string text;
   while ( in >> text )                                         // read item by item while some still available
   {
      if ( filter( text ) == word )                             // if word is found (up to filtering)
      {
        getline( in, text );                                    //    ... dump the rest of the line
        return true;                                            //    ... and return ready to read the next line
      }
   }
   return false;                                                // if we got here then word wasn't found
}

//======================================================================

int main()
{
   string word, filename, line;
   int jump;

   cout << "Input filename: ";   cin >> filename;
   cout << "Input word: ";       cin >> word    ;
   cout << "Input jump: ";       cin >> jump    ;
   
   ifstream in( filename );

   // Find word
   if ( !findWord( in, word ) )
   {
      cout << "Word not found";
      return 0;                                                 // returns, unsuccessful, to operating system
   }

   // Find the jump'th line after
   if ( !getNthLine( in, jump, line ) )                         // goes forward jump lines to work out condition
   {
      cout << "Can't find " << jump << " more lines";
      return 0;                                                 
   }
   cout << "\nLine " << jump << " afterwards is:\n" << line << '\n';
}


Input filename: gettysburg.txt
Input word: consecrate
Input jump: 11
Line 11 afterwards is:
government of the people, by the people, for the people,



Test file (gettysburg.txt):
   Four score and seven years ago our fathers brought forth on this continent
a new nation, conceived in Liberty, and dedicated to the proposition that all
men are created equal.
   Now we are engaged in a great civil war, testing whether that nation, or
any nation so conceived and so dedicated, can long endure. We are met on a
great battle-field of that war. We have come to dedicate a portion of that
field, as a final resting place for those who here gave their lives that that
nation might live. It is altogether fitting and proper that we should do this.
   But, in a larger sense, we can not dedicate - we can not consecrate - we
can not hallow - this ground. The brave men, living and dead, who struggled
here, have consecrated it, far above our poor power to add or detract. The
world will little note, nor long remember what we say here, but it can never
forget what they did here. It is for us the living, rather, to be dedicated
here to the unfinished work which they who fought here have thus far so nobly
advanced. It is rather for us to be here dedicated to the great task
remaining before us - that from these honored dead we take increased devotion
to that cause for which they gave the last full measure of devotion - that we
here highly resolve that these dead shall not have died in vain - that this
nation, under God, shall have a new birth of freedom - and that
government of the people, by the people, for the people,
shall not perish from the earth.


Last edited on
thank u guys, and yeah i can open files on c++ but i didnt know how to search for a word neither how to jump 11 after finding it, thanks!
Topic archived. No new replies allowed.