Trying to read a single character at a time into a

2019-09-21 04:14发布

问题:

I am a CS student working on a c++ project. We have been instructed to declare a struct and use it to read in an array of chars and keep a tally of how many letters are used in the string. We are not allowed to use a string; it MUST be an array of our declared struct. The input must be as long as the user wants; the code has to be able to accept new lines of input and be terminated by '.' I'm really struggling here. I don't even know where to begin. I've thrown together some code as best-guess for what to do, but it crashes after pressing "." then enter, and I don't know why.

//declare struct
struct data
{
    int tally = 0;
    char letter;
};

//size of string to read in at a time
const int SIZE_OF_CHUNK = 11;
int main()
{
//input chunk of struct
data    input[SIZE_OF_CHUNK];
int     placemark,
        length;

cout << "Enter sequence of characters, '.' to terminate:" << endl;

do
{
    for (int index = 0; (input[index].letter != '\0') && (input[index - 1].letter != '.'); index++)
    {
        cin >> input[index].letter;
        placemark++;
    }

    //I intend to put something here to handle if the code
    needs to read in another chunk, but I want to fix the crashing
    problem first
}
while (input[placemark].letter != '.');

//print out what was read in, just to check
for (int index = 0; input[index].letter != '\0'; index++)
{
    cout << input[index].letter;
}

return 0;
}

I've tried looking up how to read in a single character but haven't found anything helpful to my circumstances so far. Any tips on what I'm doing wrong, or where I can find helpful resources, would be very much appreciated.

回答1:

Are you sure you must use a declared struct?

If you just want to count the number of times a character has appeared, you don't need to store the character; you just need to store the number of times it appeared. So just unsigned lettersCount[26], and each index maps to a letter (i.e. index 0 means a, index 1 means b). Whenever a letter appears, just increase the count of that index.

You can map a letter to the index by making use of ASCII. Every letter is represented by a decimal number that you can look it up at ASCII table. For example, the letter a is represented by the decimal value 97, b is 98 and so on. The number increases successively, which we can make use of. So if you want to map a letter to an index, all you need to do is just value - 97 or value - 'a'. For example, if you read in the letter a, take away 97 from that and you'll get 0, which is what you want. After getting the index, it's just a simple ++ to increment the count of that letter.

Regarding the treatment of uppercase and lowercase (i.e. treat them the same or differently), it'll be up to you to figure it out how to do it (which should be fairly simple if you can understand what I've explained).