Question

I am a beginner to C++ and have been pondering this problem for quite a while, but I'm finding myself unable to come up with a solution and was hoping I could find some direction here.

I have an input file that will contain any number of ASCII characters (ex: hello, world; lorem ipsum; etc.). My program will read this file and count the frequency of each ASCII character, outputting the end counts when EOF is reached. I believe I need to use array[128] for the counters, but besides that, I'm totally stuck.

Here's what I have so far (it's not much and only reads the characters from the file):

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main(void)
{
    ifstream inputFile;
    string infile;
    char ch;
    //char ascii;
    //int asciiArray[128] = {0};

    // Gets input filename from user, checks to make sure it can be opened, and then
    // gets output filename from user.
    cout << "Please enter your input filename: ";
    cin >> infile;

    inputFile.open(infile.c_str());

    if (inputFile.fail())
    {
        cout << "Input file could not be opened. Try again." << endl;
        exit(0);
    }

    // Gets the first character of the input file.
    inputFile.get(ch);

    while(!inputFile.eof())
    {
        inputFile.get(ch);
    }

    // Closes the input file
    inputFile.close();

    return 0;
}

Any direction or help would be greatly appreciated. I have a feeling I will need to use pointers to solve this...but I've just barely started covering pointers, so I'm very confused. Thanks!

Edit: I removed some variables and it's working now, looks like I forgot them there while I was brainstorming. Sorry for leaving it unworking and not mentioning why; I won't do that again!

Was it helpful?

Solution

You should write your loop as:

while(inputFile >> ascii)
{                    
    asciiArray[ascii]++;
}

Note that I don't directly check for eof in the loop condition since that's almost always wrong.

Also you should be sure that your file is indeed written with ascii characters only. Since any character outside the ascii range would result in an out of bounds access to the asciiArray.

OTHER TIPS

In regular Ascii you have 128 chars... of which each char can be evaluated as an int. That is the key in solving this puzzle.

Just remember you have 128 possible chars, an array with 128 values, and each char represents a number from 0-127.

Also recall that you can do stuff like this:

int i = 97;
char a = i;
char b = a + 1;

cout << (int)i << (int)a << (int)b << endl;
// 979798
cout << (char )i << (char )a << (char )b << endl;
// aab
cout << i << a << b << endl;
// 97ab

As far as pointers go, the only way I would see them as being used is if you used pointer notation instead of array notation while manipulating your variable asciiArray

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top