In the simplest case you're just looking for the number of '\n'
characters in the file.
So let's say that you've successfully opened the file to: ifstream pFile
then you can use an istreambuf_iterator
to count those:
const auto numLines = count(istreambuf_iterator<char>(pFile), istreambuf_iterator<char>(), '\n')
A couple comments here:
- The this
count
operation will consume everything in pFile
's buffer, meaning you'll need to call pFile.seekg(0, ios_base::beg)
- Picking and choosing values to read from an
ifstream
indicates a bad smell in code. It's likely that the file format was improperly conceived, or that the program will subsequently need to re-stream the remainder of file contents. The 2nd option seems to be true in your case, as you seek to illegally set the size of an array with a value found at runtime:
The reason I need a constant int
is so I can set array to that size
EDIT:
When you say you want to use numLines
to "right an array"[sic], my assumption is that the only reason that you would have needed your array to be that size is that you're going to stream each line from a file into your container, that is you're going to stream the entire file once to calculate the size then stream the entire file again to populate your container. Here's what you should do instead:
vector<string> lines;
for(string line; getline(pFiles, line);) {
lines.push_back(line);
}
Now lines
will contain your entire file, with each element being a line. If numLines
would have been important to you, instead you can use size(lines)
.