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?
#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 ) returnfalse ;
for( std::size_t i = 0 ; i < word.size() ; ++i )
if( word[i] != str[pos+i] ) returnfalse ;
returntrue ;
}
// 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 ) ) returntrue ;
returnfalse ;
}
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' ;
}
}