'How to find the amount of numbers, lowercase and uppercase letters from a file?
I am attempting to write a program that counts the amount of lowercase letters, uppercase letters and numbers from a .txt file but I am running into some issues. How would I go about this? I have included what my .txt file looks like below. Any help will be greatly appreciated. Thank you.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
int uppercase_total, lowercase_total, digits_total;
uppercase_total = 0;
lowercase_total = 0;
digits_total = 0;
char uppercase[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char lowercase[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char digits[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
ifstream inFile("text.txt");
while (inFile >> uppercase) {
for (int i = 0; i < 1; i++) {
cout << "The uppercase count is " << uppercase_total << endl;
}
}
while (inFile >> lowercase) {
for (int i = 0; i < 1; i++) {
cout << "The lowercase count is " << lowercase_total << endl;
}
}
while (inFile >> digits) {
for (int i = 0; i < 1; i++) {
cout << "The digit count is " << digits_total << endl;
}
}
return 0;
}
Solution 1:[1]
It's actually really easy. You just need to read the file one character at a time and just check if it's between 0-9, a-z, or A-Z. This is done with 3 simple if statements:
char ch;
while (inFile >> ch) {
if ('a' <= ch && ch <= 'z')
lowercase_total++;
if ('A' <= ch && ch <= 'Z')
uppercase_total++;
if ('0' <= ch && ch <= '9')
digits_total++;
}
cout << "The uppercase count is " << uppercase_total << endl;
cout << "The lowercase count is " << lowercase_total << endl;
cout << "The digit count is " << digits_total << endl;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |