Hello,
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?
Thank you.
#include <iostream>
#include <fstream>
#include <istream>
#include <string>
usingnamespace std;
int main()
{
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;
string line;
cout << "Enter the file name: "; // obtaining the file name from the user
cin >> fileName;
seedFile.open(fileName, ios::in); // opens file
if (!seedFile)
{
cout << "This file could not be opened/found!";
}
else
{
cout << "File was opened successfully." << endl;
}
while (getline(seedFile, line));
{
++numOfLines;
}
/*while (!seedFile.eof()) // I used this w/one char at a time, but it didn't work
{
char ch;
seedFile.get(ch);
if (ch == '\n' ||ch == '\0');
numOfLines++;
seedFile.get(ch);
}
*/
cout << numOfLines << endl;
seedFile.close();
fflush(stdin);
getchar(); // to see the output before the window closes
return 0;
}
That totally fixed it :) Thank you for your quick response.
Is it correct that the semicolon terminated the while loop after one iteration and that is why I was getting 1 as the number of lines no matter how many lines there really were?
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
while (condition)
statement;
or
1 2 3 4 5 6
while (condition)
{
group;
of;
statements;
}
What happens if there is a semicolon on the first line, like this:
1 2
while (condition);
statement;
The actual meaning is this:
1 2 3 4
while (condition)
; // 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.