#include <iostream>
#include <fstream>
using namespace std;
void countWords(fstream &myText, int word);
void countLines(fstream &myText, int lines);
void wordLength(fstream &myText, int length);
int main()
{
char textLine[100];
int lines = 0, word = 0;
fstream myText;
myText.open("myText.txt", ios::in | ios::out);
if (!myText)
{
cout << "Cannot open file - myText.txt" << endl;
exit(1);
}
cout << "Enter some lines of text. (Blank to exit)" << endl;
cin.getline(textLine, 100);
while (textLine[0] != '\0')
{
cout << "Enter another line of text." << endl;
cin.getline(textLine, 100);
}
myText.seekg(0);
cout << "The text in this file is " << endl;
myText.getline(textLine, 100);
countWords(myText, word);
countLines(myText, lines);
myText.close();
return 0;
}
void countWords(fstream &myText, int word)
{
char ch, previousChar = NULL, blank = ' ';
int numberChars = 1;
while (!myText.eof())
{
myText.get(ch);
cout << ch << endl;
numberChars++;
if (ch == blank && previousChar != blank)
word++;
}
cout << "There are " << word + 1 << " word(s) in this file." << endl;
}
void countLines(fstream &myText, int lines)
{
char ch, endOfLine = '\n';
int numberChars = 1;
while (!myText.eof())
{
myText.get(ch);
cout << ch << endl;
numberChars++;
if (ch == endOfLine)
lines++;
}
cout << "There are " << lines - 1 << " line(s) in this file." << endl;
}
Hello,
I'm trying to make a program which outputs the text in a text file and also
calculate the number of lines in the file, the number of words and the average
word length. I haven't tried to do the average word length yet, so my program
ignores that for the time being. My program compiles, but when I debug, one character is printed per line and
I'd like for it to print as it appears in the text file. Here's my code, and
I'm sorry if I did any of my posting wrong, this is my first time and I'm also
still new to C++ programming.