Reading number of lines from a text file.

Whenever the code runs, the number that is returned is a gigantic negative number.

Here is the output: "There are -1077611113 Lines in the file."


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
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>

using namespace std;
using std::ofstream;
using std::ifstream;

int getLineNumber();
void checkFile();

int main(int argc, char* argv[]){
	int x = getLineNumber();
	
	cout << "There are " << x << " Lines in the file." << endl;

	//cout << "--------Hello and welcome to Anikan's Phone Book application!--------" << endl;
	//cout << "Here are all of the contacts listed in your phone book:" << endl;
	//cout << "_______________________________________________________" << endl;


	//for(int i = 0; i < 100; i ++)
}

int getLineNumber(){
	string line;
	int numberOfLines;
	ifstream dataLogFile("contacts.txt");

	if(dataLogFile.is_open()){
		while(getline(dataLogFile, line)){
			numberOfLines++;
		}
		//dataLogFile.close();
	}

	return(numberOfLines);
}

void checkFile(){
	ofstream outputFileStream("contacts.txt");

	if(!outputFileStream)
		cout << "The File doesn't exist!" << endl;
	else
		cout << "The File does exist!" << endl;
}
This is because you never initialize numberOfLines in getLineNumber(). Just set it to zero after you declare it and it will work better.
Topic archived. No new replies allowed.