HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

What's in your file?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fileyourwhat

Problem

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 
#include 
#include 

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;
}

Solution

-
You can pass data by const& as it's not being modified.

-
ARRAY_LENGTH should probably be an unsigned type, such as std::size_t.

-
Just to stay safe, terminate the program if the file cannot be opened:

if (!file)
{
    std::cerr << "file cannot be opened";
    return EXIT_FAILURE;
}


-
You do not really need to call close() here. It would only be necessary for checking for errors, otherwise the destructor will do this for you. It shouldn't leak any resources.

Code Snippets

if (!file)
{
    std::cerr << "file cannot be opened";
    return EXIT_FAILURE;
}

Context

StackExchange Code Review Q#68898, answer score: 8

Revisions (0)

No revisions yet.