-
Notifications
You must be signed in to change notification settings - Fork 8
/
char-count.cpp
94 lines (75 loc) · 2.02 KB
/
char-count.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "Counter.h"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
// This is the main function for the Character Count test cases.
// It runs through a list of files, and either increments or decrements
// the count of each letter. Every time it sees a whitespace character,
// it toggles between increment and decrement mode. It prints per-file
// results, and the cumulative result for all files.
// You can modify this, but Gradescope will use the original.
const char* ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
void print_header() {
for(int i = 0; i < 26; ++i) {
std::cout << " " << ALPHA[i] << ALPHA[i + 26];
}
std::cout << " Filename\n";
}
void print_results(const char* filename, const Counter& counter) {
std::string str = "?";
for(int i = 0; i < 26; ++i) {
str[0] = ALPHA[i];
int cap = counter.get(str);
str[0] = ALPHA[i + 26];
int low = counter.get(str);
std::cout << std::setw(6) << (cap + low);
}
std::cout << " " << filename << std::endl;
}
int main(int argc, char** argv) {
if(argc < 2) {
std::cerr << "USAGE: " << argv[0] << "[filename] [...]\n";
return 1;
}
Counter totals;
print_header();
for(int argi = 1; argi < argc; ++ argi) {
std::ifstream stream(argv[argi]);
if(stream.fail()) {
std::cerr << "ERROR: Could not open file: " << argv[argi] << '\n';
continue;
}
char c;
bool inc = true;
std::string str = "?";
Counter counter;
while(stream.get(c)) {
if(isspace(c)) {
inc = !inc;
continue;
}
else if(!isalpha(c)) {
continue;
}
str[0] = c;
if(inc) {
counter.inc(str);
totals.inc(str);
}
else {
counter.dec(str);
totals.dec(str);
}
if(counter.get(str) == 0) {
counter.del(str);
}
if(totals.get(str) == 0) {
totals.del(str);
}
}
print_results(argv[argi], counter);
}
print_results("TOTAL", totals);
return 0;
}