gpt4 book ai didi

c++ - 为什么这个函数与 strpbrk() 一起工作?

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

当我尝试将定界符放入 vector::operators 时,为什么我的程序会崩溃?我正在尝试制作一个可用的计算器,我需要按顺序找到输入字符串的所有运算符。所有必要的库都包括在内,当我只使用 2 个数字和 1 个运算符时,代码就可以工作了。是我循环使用不正确的问题吗?我也有一个类似的功能来查找在相同位置有效和崩溃的数字。

vector<char>operators;

int main()
{
string input;
cin >> input;
find_operators(input);
}

void find_operators(string X)
{
char * cX = new char[X.length()];
strcpy(cX, X.c_str());
char * delimiter = strpbrk(cX,"+*-/");
operators.push_back(*delimiter); //this worked
while (delimiter != NULL)
{
delimiter = strpbrk(delimiter+1, "+-*/");
cout << "OK"; //makes it to this point then crashes
operators.push_back(*delimiter); //this doesn't work
}
delete[] cX;
}

最佳答案

您的代码有几个问题。第一:

char * cX = new char[X.length()];
strcpy(cX, X.c_str());

不正确,因为您没有考虑 cX 中需要的空终止符。 length() 只返回字符串中的字符数,不计算空终止符。要解决这个问题,您需要做的就是:

char * cX = new char[X.length() + 1];
strcpy(cX, X.c_str()); // ^^^^ add one to the size

您的第二期在:

while (delimiter != NULL)
{
delimiter = strpbrk(delimiter+1, "+-*/");
cout << "OK"; //makes it to this point then crashes
operators.push_back(*delimiter); //this doesn't work
}

您检查 delimiter 是否不为空,然后使用 strpbrk() 重新分配它。如果 strpbrk() 返回 NULL,则 operators.push_back(*delimiter) 将失败,因为您正在取消引用空指针。您应该能够将代码更改为以下内容以使其正常工作:

//...
char * delimiter = strpbrk(cX,"+*-/"); // get operator
while (delimiter != NULL) // keep looping while we have an operator
{
operators.push_back(*delimiter); // add the operator to the vector
delimiter = strpbrk(delimiter+1, "+-*/"); // find the next operator
}
//...

关于c++ - 为什么这个函数与 strpbrk() 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490163/

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