What code do I use to count the characters and lines in a .txt file?

Here is my sample text file (love.txt):

I love you
all day and
all night
forever and
ever.

Here is my program. I HAVE to create a separate function that counts the characters and lines in the text file. I think I have everything set up correctly in "int main()" & "Function Prototypes", I just have no clue what to write inside the "Function: countCharsLines". Please help. A friend of mind told me to use a string to count the lines & characters in the file but I don't know how to even go about writing that code.

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

// Function Prototypes
void readFilename(ifstream&, string&);
void countCharsLines(ifstream&, int&, int&);

int main()
{
// Variables
ifstream inFile;
string filename;
int countLines;
int countChars;

// Function Calls
readFilename(inFile, filename);
countCharsLines(inFile, countLines, countChars);

return 0;
}

// Function: readFilename
void readFilename(ifstream &inFile, string &filename)
{
// Reads in file name.
cout << "Please enter the file name you wish to open." << endl;
getline(cin, filename);
inFile.open(filename.c_str());

// Displays error message if file is not found.
if (!inFile)
{
cout << "This file did not open properly and the program will now terminate.\nPlease make sure the spelling of the file is correct." << endl;
}
}

// Function: countCharsLines
void countCharsLines(ifstream &inFile, int &countLines, int &countChars)
{
}
Last edited on
Try using getline() in a while(inFile) loop to store each line into a string. Then store the string's length into countChars and store the increment +1 of each loop into countLines.
Last edited on
Topic archived. No new replies allowed.