gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:04:21 25 4
gpt4 key购买 nike

在过去的两个小时里,我一直在尝试不同的方法来防止我在运行该程序时不断遇到的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com