在过去的两个小时中,我尝试了不同的方法来防止运行此程序时不断出现的APPCRASH错误,但是我没有任何运气。基本上,所有这些都是用于分配的简单单词计数程序。它会正常工作,直到显示程序运行时发现的字数为止。此时,它只冻结一两秒钟,然后弹出并显示APPCRASH错误,然后关闭。我不知道为什么会这样,有人在乎让我知道我要去哪里了吗?

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

最佳答案

您正在分配1个字节,并期望在那里容纳100个字节:

char *userInput = new char;


您应该改写:

char *userInput = new char[101];


更好的是,避免使用原始指针,C字符串和new。在C ++中使用std::string

关于c++ - 字符数组和字数统计,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20076463/

10-12 14:37
查看更多