how can i open a file from a program and count the lines in the files and return the total amount of lines in the file to the program?
Printable View
how can i open a file from a program and count the lines in the files and return the total amount of lines in the file to the program?
Maybe not the most efficient method, but probably the easiest for text files
Code:#include <fstream>
#include <iostream>
#include <string>
int main(){
std::ifstream in;
std::string filename;
std::cout << "Enter name of file" << std::endl;
std::getline(std::cin,filename);//get name of file
in.open(filename.c_str());//open it
if(!in.is_open()){//see if open was successful
std::cout << "Could not open " << filename;
return 1;
}
std::string dummy;//dummy string to hold read info
int n = 0;//line count
dummy.reserve(500);//try reserve memory (not needed, but may help)
while(!in.eof()){//while not at end of file
std::getline(in,dummy);//read a line into a string
++n;//increase count
}
std::cout << "Total line count = " << n;
}
I think you have to count how many times the '\n' appeared in the text file.