Counting lines in a txt file

So I have a file that has seven lines of text and I have to count them.
This program correctly counts the correct amount of lines of text if I use the . as the delimiter but I tried it with the \n and it would always return as 0. What seems to be the problem?

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
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int file(string &);

int main()
{
    string fileName;

    cout << "Enter the name of your file to count the number of lines in your file. " << endl;
    getline(cin, fileName, '\n');

    cout << "The number of lines that this file has is: " << file(fileName) << "lines. ";
    
    cout << endl;

    return 0;
}

int file(string &fileName)
{
    char newLine = '.';
    int numLines = 0;
    string text;
    ifstream openFile(fileName.c_str());

    cout << endl;

    if(!openFile)
    {
        cerr << "Error, file does not exist. " << endl;
        exit(EXIT_FAILURE);
    }

    while(getline(openFile, text, '\n'))
    {
        for(unsigned int i=0; i< text.length(); i++)
        {
            if(text.at(i) == newLine)
            {
                numLines++;
            }
        }
    }

    return numLines;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main () {
string s;
int sTotal;

ifstream in;
in.open("E:/C++/CPP/inf.txt");

while(!in.eof()) {
	getline(in, s);
	sTotal ++;	
}

cout << sTotal;

in.close();	
return 0;
}
Topic archived. No new replies allowed.