how to count total number of selected lines

i want to count the total number of the selected lines (hello world) in my program. My program is able to give the line number of the selected line but i want the total number of lines to be displayed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void total_lines(const string&)
{
 string data;
 int line=0;
 string dest[2]={"hello world"};
 ifstream file;
 file.open("hello.txt",ios::in);
 while(!file.eof())
 {
     getline(file,data);
     line++ ;
     for(int i=0;i<1;i++)
         if(data.find(dest[i])!=string::npos)
             cout<<line <<" : "<<dest[i] << endl;
 }
}
int main()
{
    total_lines("hello.txt");
}




1
2
3
4
5
hello.txt
hello world
blabla
hello world
hello world


1
2
3
4
5
required output:
2 : hello world
4 : hello world
5 : hello world
total : 3
Last edited on
at the beginning of your function declare an int total = 0;

change the for loop like so : for(int i = 0 ; i < 1 ; i ++ , total ++ )

then cout the value.
where should i cout the value of total.. i am trying to do it this way
1
2
3
if(data.find(dest[i])!=string::npos)
             cout<<line <<" : "<<dest[i] << endl;
             cout<<total<<endl;



and the output is :
1
2 : hello world
2
3
4 : hello world
4
5 : hello world
5
6



when i place after the while loop is ended the output is similar to:
2 : hello world
4 : hello world
5 : hello world
6



i only want to print the total number of lines with"hello world". please help
Last edited on
Your loop is useless, it does only one iteration. If you think that amount of strings to search will grow, you can leave it, else replace it with its boby content.

Do you need to output number of found lines? In this case you did almost everyhing right, but placement of total increase is incorrect: you need to increment it if line matchs some other string, so you should put in the if statement body.
You want output after you processed your file, so you need to output total after while loop.

Also your while loop is incorrect. Do not loop on eof. It is almost always wrong. It does not stop when needed. You can see it in your output: your loop processes 6 lines out of 5
Correct approach is to loop on input operation: while(getline(file,data)) { ///...
Last edited on
Topic archived. No new replies allowed.