checking for a word from a file

I am trying to output the position of a word from a file.

I ask the user for a sentence.
1
2
std::string line;
  std::getline(std::cin, line);


i input the sentence into a file
1
2
3
std::fstream input;
input.open("input.txt");
input << line;


i ask them what word they want to find
1
2
std::string word;
std::cin >> word;


im stuck on how to check for the word.
any tips are greatly appreciated!
use a for loop
Last edited on
First of all you need read the sentence from the file the same way as you got the input from the user that is by means of getline

std::getline( input, line );

Then you should use std::istringstream and std::istream_iterator. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::istringstream is( line );

auto it = std::find( std::istream_iterator<std::string>( is ),
                            std::istream_iterator<std::string>(),
                            word );

if ( it == std::istream_iterator<std::string>() )
{
   std::cout << "Word \"" << word << "\" is not present\n";
}
else 
{
   std::cout << "Word \"" << word << "\" is present\n";
}
Last edited on
I was able to implement somewhat the linked program from Rehan FASTian but unfortunately im not gettting the output i want.

I am trying to get the position in the line where the word was found, and output that.

here is what i have so far, its simply outputting a weird position that does not make sense. like 20 characters ahead of where it actually is.

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
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>

int main()
{
	std::cout << "please enter a sentence. \n";

	std::string line;

	std::getline(std::cin, line);

	std::ofstream input;

	input.open("input.txt");

	input << line;

	input.close();

	std::cout << "What word would you like to find? \n";

	char word[10];

	std::cin.getline(word, 10, '\n');
	int size_of_word;
	for ( size_of_word = 0; word[size_of_word] != '\0'; size_of_word++ );

	std::ifstream out("input.txt");

	char sentence[200];
	int i = 0;
	bool found = false;

	while ( !out.eof() )
	{
		out.getline(sentence, 200, '\n');
		for ( int j = 0; sentence[j] != '\0'; j++ )
		{
			if(sentence[j] == word[i])
			{
				++i;
			}
			else
			{
				i = 0;
			}
			if(i >= size_of_word )
			{
				int n = out.tellg();
				std::cout << "Found at position: " << n << std::endl;
				found = true;
			}
		}
	}
	if(!found)
	{
		std::cout << "NOT Found!" << std::endl;
	}

	out.close();

	system("pause");
	return 0;
}
Topic archived. No new replies allowed.