Another more simple project from my CS1 class that I didn't upload while I was sick last week:
Write a program that computes all of the following statistics for a file and outputs the statistics to both the screen and to another file: the total number of occurrences of characters in the file, the total number of non-whitespace characters in the file, and the total number of occurrences of letters in the file.
I must use at least two functions in this project. In addition, I am also supposed to count and output the number of occurrences of each character.
fileStats.cpp
:
/**
* @file fileStats.cpp
* @brief
* @author syb0rg
* @date 10/23/14
*/
#include <iostream>
#include <sstream>
#include <fstream>
constexpr int ARRAY_LENGTH = 128;
struct Data
{
size_t total = 0;
size_t nonWhite = 0;
size_t letters = 0;
size_t charCount[ARRAY_LENGTH] = {0};
};
std::string constructString(Data data)
{
std::stringstream sstm;
sstm << "Number of characters: " << data.total << "\n";
sstm << "Number of non-whitespace characters: " << data.nonWhite << "\n";
sstm << "Number of letters: " << data.letters << "\n" << "\n";
sstm << "Occurances of each character: " << "\n";
for (int i = 0; i < ARRAY_LENGTH; ++i)
{
if(data.charCount[i]) sstm << (char) i << ": " << data.charCount[i] << "\n";
}
return sstm.str();
}
void outputToFile(std::string fileName, std::string str)
{
std::ofstream out(fileName);
out << str;
out.close();
}
int main()
{
Data data;
std::ifstream file("test.txt");
char input = '\0';
while ((input = file.get()) && file.good())
{
data.total++;
data.charCount[input]++;
if(!isblank(input)) data.nonWhite++;
if(isalpha(input)) data.letters++;
}
file.close();
std::string result = constructString(data);
outputToFile("output.txt", result);
std::cout << result;
}
ARRAY_LENGTH = 128;
. Otherwise you need to validate that your character is in the correct range. \$\endgroup\$