getline and line read from file

hey guys. This is my question.
Give a file, find number of occurrences of a search string with line numbers in which this tring occurs...
My problem: my code only gives first occurrence and line number

after opening the file

my file is:

hello how r u
ok?
how r u
thanks fine
bye

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
while(!readFile.eof()){
	readFile>>noskipws;
	while(readFile.getline(filetext, 100)){
		line=line+1;
		
		for(int j=0;j<strlen(filetext);j++){
		if(filetext[j]==search[j]){
			
			count=count+1;
			
			
			}
		if(count==size){
			cout<<"line is: "<<line<<endl;
			occur=occur+1;
			count=0;	
				}
		
						
		
		}


Enter filename: search.txt
Enter text to search: how r u
line is: 3
Occurances of search 1


but how r u occurs two times!
your code only prints if (count==size) and I can't see how you use "size".

It might be as simple as removing line 8-13 & 16 but I can't say for certain with what you have posted.
Did you consider using strstr() instead of reinventing it?
http://www.cplusplus.com/reference/cstring/strstr/
your code searches only for matches starting from the beginning of the line.

Both how r u and how r u m8 will both trigger a hit, but hi how r u will not
Last edited on
My problem: my code only gives first occurrence and line number


It looks like it didn't find the first occurrence but the one that exactly matches on line 3. It skipped the one where the phrase started differently.

if(filetext[j]==search[j])
I'm not sure, but it looks like you might be comparing character 1 of the string in the file with character 1 of the string you are searching for. If the file string starts with a different character, they aren't going to match up.
Minipaa and Wildblue correct...But how am i going to bypass this error? Is there any way except by pointers? because I am only required to use cstring...thanks all
As Chervil told, use strstr()
Topic archived. No new replies allowed.