c++ - 字符数组和字数统计

标签 c++ cstring arrays

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

    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/

相关文章:

c++ - VS2013 中的静态 Qt 程序构建 - 许多 Unresolved external 问题

c++ - 如何让自定义(计时)计时器与 sleep_until 一起工作?

c++ - 显示和移动正方形

c++ - CStringT 到 char[]

Javascript - 使用reduce方法进行分组函数

java - ArrayList 与数组。为什么一个工作,一个不工作?

java - 计算不相交的有向字母

c++ - 析构函数 vs 成员函数竞赛

c++ - String is not null terminated 错误

c++ - 将 float\double 数字格式化为零填充和预设位数的 CString