Find word from text file

Hi there!

I've been struggling with finding a way to read form two text files. I have two input files "textword.txt" and "textsentence.txt".

textword.txt has
apple
orange
banana

textsentence.txt has
I like apples.
Oranges are sweet.
Monkeys like bananas.

How would I read the first word from textword.txt and find that word in the sentences of textsentences.txt, without using find(), and then output the whole sentence containing the first word from text word.txt?

Here's what I've tried...

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
 
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
	ifstream inWords, inSentences;
	inWords.open("words.txt");
	inSentences.open("sentences.txt");

	string w1;
	getline(inSentences,w1);
	bool find = 0;
	
	ofstream outFirst;
	outFirst.open("first.txt");
	
	while(!inSentences.eof())
	{
		string temp = "";
		getline(inWords,temp);
		for(int i=0 ; i < w1.size() ; i++)
		{
			if(temp == w1)
				find = 1;
			else
			{
				find = 0;
				break;
			}
		}

		if(find)
		{
			outFirst << temp;
		}

	}

	

	inWords.close();
	inSentences.close();
	outFirst.close();
	return 0;
}
Last edited on
Brute force:
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
#include <iostream>
#include <string>
#include <fstream>

// return true if the sequence of characters starting at str[pos]
// are the same sequence of characters in word
bool equal( const std::string& str, std::size_t pos, const std::string& word )
{
    // return str.substr( pos, word.size() ) == word ;

    if( word.size() > str.size() - pos ) return false ;

    for( std::size_t i = 0 ; i < word.size() ; ++i )
        if( word[i] != str[pos+i] ) return false ;

    return true ;
}

// return true if any sequence of characters in str
// is the same sequence of characters in word
bool contains( const std::string& str, const std::string& word )
{
    for( std::size_t i = 0 ; i < str.size() ; ++i )
        if( equal( str, i, word ) ) return true ;

    return false ;
}

int main()
{
    // print all lines in this file which contains the word 'const'
    const std::string word = "const" ;

    std::ifstream file( __FILE__ ) ; // open this file for input
    std::size_t line_number = 0 ;
    std::string line ;

    while( std::getline( file, line ) ) // for each line in the file
    {
        ++line_number ;
        if( contains( line, word ) ) std::cout << line_number << ".  " << line << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/09fa366403402677
Topic archived. No new replies allowed.