I am a C++ student with very limited experience. I looked through the forum, and I found some post regarding this topic, and I did what it said, but I am still getting a bad result.
I want to read a text file, and count a number of lines, so I can use it later in my program. However, I am getting 1 as a result, no matter how many lines are in the file.
Could anyone please help me understand what I am doing wrong and show me how to get the number of lines from a file the right way?
constint SIZE = 31; // array for the file name
char fileName[SIZE]; // this will hold the file name once give by the user
fstream seedFile; // file stream object for opening the file
ifstream seedFile; // for counting the lines
int numOfLines = 0;
cout << "Enter the file name: "; // obtaining the file name from the user
cin >> fileName;
seedFile.open(fileName, ios::in); // opens file
cout << "This file could not be opened/found!";
cout << "File was opened successfully." << endl;
while (getline(seedFile, line));
/*while (!seedFile.eof()) // I used this w/one char at a time, but it didn't work
if (ch == '\n' ||ch == '\0');
cout << numOfLines << endl;
getchar(); // to see the output before the window closes
Is it correct that the semicolon terminated the while loop after one iteration
Not really, that's not the exact explanation.
Think of it like this, a while loop looks like this:
1 2 3 4 5 6
What happens if there is a semicolon on the first line, like this:
The actual meaning is this:
1 2 3 4
; // empty statement is executed during each iteration of the loop
statement; // this doesn't get executed until after the loop has ended
What this means is that the while loop did in fact read all of the lines from the file. After reading the last line, the loop ended, and the program continued with the next statement, which of course was executed only once, because it was not part of the loop at all.
Great. Thank you. That helped me better understand it. I thought that the misplaced semicolon caused it somehow to ignore the condition and only execute the body of the loop only once. I appreciate your effort. Thank you again.