I'm trying to learn some coding to broaden my scope of knowledge, and I seemed to have run into a bit of a conundrum.
I'm trying to create a program to output the number of characters, digits, punctuation, spaces, words and lines that are being read in from a file.
Here is the text file I am reading in:
See Jack run. Jack can run fast. Jack runs after the cat. The cat's fur is black. See Jack catch the cat.
Jack says, "I caught the cat."
The cat says, "Meow!"
Jack has caught 1 meowing cat. Jack wants 5 cats, but can't find any more.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream lab3;
string word;
lab3.open("lab3.txt");
int countletters=0,countnum=0,countpunc=0,countspace=0,words=0,line=0;
char character,prevchar = 0;
if(!lab3)
{
cout << "Could not open file" << endl;
return 1;
}
while(lab3.get(character) && !lab3.eof())
{
if(isalpha(character))
{
countletters++;
}
if (isdigit(character))
{
countnum++;
}
if (ispunct(character))
{
countpunc++;
if (isalpha(prevchar))
{
words++;
}
}
if (isspace(character))
{
countspace++;
if (isalpha(prevchar))
{
words++;
}
}
if(character=='\n')
{
line++;
}
prevchar = character;
}
cout << "There are " << countletters << " letters." << endl;
cout << "There are " << countnum << " numbers." << endl;
cout << "There are " << countpunc << " punctuations." << endl;
cout << "There are " << countspace << " spaces." << endl;
cout << "There are " << words << " words." << endl;
cout << "There are " << line << " sentences." << endl;
lab3.close();
return 0;
}
Output:
There are 167 letters.
There are 2 numbers.
There are 18 punctuations.
There are 52 spaces.
There are 47 words.
There are 4 sentences.
Some things I am hoping to learn:
- Advice for improvements on my code for learning purposes/efficiency.
- Explanation for reading information in from a text file: whether it is letters, numbers, punctuation - whatever you may run across doing this type of data-processing.
Some things I am aware of:
using namespace std;
is not good practice - what is the best practice for real world applications?- I am a beginner and this may not be (definitely is not) the cream-of-the-crop coding.
There are 0 words
really? \$\endgroup\$