c++cstringarrays

Char arrays and word counting


I have spent the last two hours trying different methods to prevent the APPCRASH error I keep getting when I run this program, but I am having NO luck whatsoever. Basically, all this is is a simple word counting program for an assignment. It works fine up until it is to display the word count that the program found when it ran. At this point, it just freezes for a second or two, then pops up with an APPCRASH error, and closes. I don't know WHY this is happening, anyone care to let me know where I am going wrong?

    int main()
{
    //word counting programs
    char *userInput = new char;
    input(userInput);
    displayResults(wordCount(userInput), userInput);    
    return 0;
}

/***************************************
Definition of function - input         *
prompts the user to input a sentence   *
and stores the sentence into a char    *
array.                                 *
Parameter: char []                     *
****************************************/
void input(char userInput[])
{
    cout << "Enter a sentence (no more than 100 characters) and I will count the words:" << endl;
    cin.getline(userInput, 101);
}

/***************************************
Definition of function - wordCount     *
Accepts the input char array and counts*
the words in the sentence. Returns an  *
int value with the word count.         *
Parameter: char []                     *
Returns: an int with the word count    *
****************************************/
int wordCount(char* userInput)
{
    int count = 0;
    int words = 1;
    if(userInput[0] == '\0')
    {
        words = 0;
    }
    else if(userInput[0] == ' ' || userInput[0] == '\t')
    {
        cout << "Error: can not use a whitespace as the first character!" << endl;
        words = -1;
    }
    else
    {
        while(userInput[count] != '\0')
        {
            if(userInput[count] == ' ')
            {
                words++;
            }
            count++;
        }
    }
    return words;
}

/***************************************
Definition of function - displayResults*
Displays the word count for the user   *
entered input.                         *
****************************************/
void displayResults(int wordCountResult, char userInput[])
{
    if(wordCountResult == -1)
        cout << "Error reading input!" << endl;
    else if(wordCountResult == 0)
        cout << "Nothing was entered." << endl;
    else
    {
        cout << "You entered: " << userInput << endl;
        cout << "That contains " << wordCountResult << " word(s)!" << endl;
    }
}

Solution

  • You're allocating 1 byte and expect to fit 100 bytes there:

    char *userInput = new char;
    

    You should write instead:

    char *userInput = new char[101];
    

    Better yet, avoid using raw pointers, C-strings and new. Use std::string in C++.