So I'm trying to count the number of lines in a text file. I think I got it working, but it seems I can't do further correct processing on the text file, maybe because getline extracts the data? The operations I want to perform include inputting values read from the file into an array (This works correctly if I comment out the code for counting the lines, but the output is wrong if I include the code).

string fileName;
   cin >> fileName;
   ifstream inData; fileName.c_str() );
   if ( !inData ) 
      return 0;
   size = 0;
   string line;
   while ( !inData.eof() )
       getline(inData, line);

that's because the loop is wrong. You don't need to use eof() at all

while( getline(inData, line) )
    // do other stuff here

There's still a problem : /, I need the number of lines before I can correctly do the other stuff.

Did some reading, I got it working I think. I just had to add:

inData.close(); fileName.c_str() );

to clear the stream and read from the beginning of the file again.

Thanks for the help.

you do not have to close and then reopen the file; inData.clear() ; inData.seekg(0) ; is more efficient.
> I need the number of lines before I can correctly do the other stuff.
you do not; use a vector instead of a c-style array:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std ;

int main()
   ifstream file( __FILE__ ) ;
   string line ;
   vector<string> lines ;
   while( getline( file, line ) ) lines.push_back( line ) ;
   cout << "#lines: " << lines.size() << '\n' ;
commented: Good ~SpS +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.