no of lines in file..

closed account (z0XLy60M)
I need a program in c++ that counts the number of lines in a given text file...

idk how to even begin...
Pls help...and explain too.

:)

Use the getline function.
Keep calling it until it doesn't work.
Count how many times you called it.
closed account (z0XLy60M)
And how am I supposed to know when it stops working..?

I want a simple program using fstream, loops, 'if'...etc.
Noob friendly please..

:)
Something like this:
1
2
3
4
while(getline(in, line))
{
  count++;
}
closed account (z0XLy60M)
I repeat, noob friendly please...

what are those "in" and "line" thingys ... ?

keywords ? constants ?

:/
Tell me, are you familiar with the idea of looking things up? Start by looking up "getline" in the context of C++.
closed account (z0XLy60M)
Teri maa ki chut mei naariyal phod dunga,bhen ke laude..
:D
I'm giving you this because you do not sound like a programming student.
If you are, you should have already learned this. If you are a student and don't already know this your going to fail. Me giving it to you isn't going to change that unless you apply yourself.

This is the basics of what you want, it doesn't check to see if the file exist, or give you a error if the file is not found.

There are no comments, so you will need to look up what each line does and how it works if you wish to change it, but it's pretty noob friendly.

This is the base for adding more features, such as you can change it to show one screen at a time; search for a word or string in a file; if the file has numbers you can do math; with a few changes you can write to a file, but you need to learn what every line in this program does before you can begin the next step: changing it to do what you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>

using namespace std;

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

    while (std::getline(myfile, line))
	{
        ++number_of_lines;
//        cout << number_of_lines << ": " << line << endl;
	}
//    cout << "------------------------" << endl;
    std::cout << "Number of lines in file: " << number_of_lines;
	return 0;
}
Topic archived. No new replies allowed.