[Solved]Program to count the number of lines in a file doesn't work
Hi!
I'm working on a program that will count the number of lines ( where a line is everything before a '\n' control character ) in an ASCII file.
Here is what I currently have:
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
|
#include <iostream>
#include <fstream>
#include <cstdlib>
int main ( int argc, char * argv [ 2 ] )
{
std::ifstream input_file;
char buffer [ 100 ];
unsigned int line_count ( 0 );
if ( argc < 2 )
{
std::cerr << "Fatal error: wrong number of arguments. \n"
<< "Usage: " << argv [ 0 ] << " [filename]. \n";
exit ( EXIT_FAILURE );
}
input_file.open ( argv [ 1 ] );
if ( input_file.bad ( ) )
{
std::cerr << "Fatal error: couldn't open file \""
<< argv [ 1 ]
<< "\".\n";
exit ( EXIT_FAILURE );
}
while ( input_file.getline ( buffer, sizeof ( buffer ) ) )
{;
for ( unsigned int index = 0; index < 99; ++ index )
{
if ( buffer [ index ] == '\n' )
{
++ line_count;
}
}
}
std::cout << "There are " << line_count << " number of lines in file \""
<< argv [ 1 ] << "\". \n";
return ( 0 );
}
|
Now the problem is that each time when I run this program on a file, the number of lines is 0. This is obviously incorrect.
I'm assuming that my expression for while isn't correct, but I wouldn't know how to fix it.
Does anybody know how I can fix this program?
Thanks in advance!
Last edited on
getline discards the '\n' it finds.
I don't see your logic. You know that getline will get one line, so you could ++line_count immediately.
Thanks, you've fixed my problem! :)
Topic archived. No new replies allowed.