counting number of lines

I have a file that contains thousands of numeric entries sorted into four columns. The structure of the data looks something like the following:

3 0.2 0.5 6.2
4 0.1 0.6 6.2 //Track 1
2 0.8 0.5 0.6

2 0.6 0.5 0.4
1 0.8 0.4 2.1 //Track 2
2 0.5 0.4 2.4
4 0.6 0.8 2.5

2 0.3 0.1 0.9 //Track 3
8 0.6 0.8 0.7

The data is grouped into tracks where a new track starts after each line break as shown above (in the actual data there are thousands of tracks). Notice each track has a varying number of lines. The goal of the program will be to read through the data and count the number of lines in each track. The output of the program would look something like the following:

Number of lines in Track 1: 3
Number of lines in Track 2: 4
Number of lines in Track 3: 2 .... and so on

So far I have written the following code which I believe should read the total number of lines in the data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <istream>
using namespace std;

int main() {
	int number_of_lines = 0;
    std::string line;
    std::ifstream myfile("file.dat");

    while (std::getline(myfile, line))
	{
        ++number_of_lines;
	}

    std::cout << "Number of lines in text file: " << number_of_lines;

	system("pause");
	return 0;
}


This code, however, will just count the total number of lines and not the number of lines per track. I'm not quite sure where to go from here. How do I make this program output the number of lines per track?

Last edited on
here is your new code do exactly what are you wish
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
#include <iostream>
#include <fstream>
#include <istream>
using namespace std;

int main() {
	int number_of_lines = 0, track=1;
    string line;
    ifstream myfile("a.txt");
    while (myfile.good ())
	{
        getline(myfile, line);
        cout << line <<  endl;
        if (line=="")
        {
            cout << "Number of lines for track "<< track << " is "<<number_of_lines<< endl; 
            number_of_lines=0;
            track++;
        }
        else 
        {
            ++number_of_lines;
        }
        
	}
	cout << "Number of lines for track "<< track << " is "<<number_of_lines<< endl; 
	system("pause");
	return 0;
}
Great! Thanks a lot. Code works as I intended.
Topic archived. No new replies allowed.