Why does my program crash when I try to put delimiter into vector::operators?I'm trying to make a working calculator and I need to find all the operators of the input string in order. All the necessary libraries were included, and the code worked when I was only using 2 numbers and 1 operator. Is the problem that I used the loop incorrectly? I also have a similar function to find the numbers that works and crashes in the same spots.
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;
}
You have a couple issues with your code. First:
char * cX = new char[X.length()];
strcpy(cX, X.c_str());
Is incorrect as you are not accounting for the null terminator that you need in cX
. length()
only returns the number of character in the string and does not count the null terminator. To fix that all you need to do is:
char * cX = new char[X.length() + 1];
strcpy(cX, X.c_str()); // ^^^^ add one to the size
The second issue you have is in:
while (delimiter != NULL)
{
delimiter = strpbrk(delimiter+1, "+-*/");
cout << "OK"; //makes it to this point then crashes
operators.push_back(*delimiter); //this doesn't work
}
You check if delimiter
is not null and then you reassign it using strpbrk()
. If strpbrk()
returns NULL
then operators.push_back(*delimiter)
is going to fail because you are dereferencing a null pointer. You should be able to change your code to the following to get it to work:
//...
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
}
//...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.