I am getting std::logic_error: basic_string::_s_construct null not valid in this program. How can I solve that? I already tried a previously posted solution but could not correct it myself.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
stack<string> s;
string temp, exp[] = "abc-+de-fg-h+/*";
string ch1 = 0, ch2 = 0, ch = 0;
int sizeExp = sizeof(exp)/sizeof(*exp);
for(int i=0; i < sizeExp ; i++) {
ch = exp[i];
if (ch == "*" || ch == "/" || ch == "+" || ch == "-") {
if (s.empty() && sizeof(temp) != sizeof(exp)) {
cout << "Error in Expression." << endl;
}
else {
if (sizeof(s.top()) != sizeof(char)){
ch1 = s.top();
s.pop();
ch2 = s.top();
temp = '(' + ch2 + ')' + exp[i] + '(' + ch1 + ')';
s.push(temp);
}
else {
ch1 = s.top();
s.pop();
ch2 = s.top();
temp = ch2 + exp[i] + ch1;
s.push(temp);
}
}
}
else {
s.push(exp[i]);
}
}
cout << temp << endl << "Is your Infix Expression for ";
cout << exp;
return 0;
}
The issue is with statements of the sort std::string str = 0;. This leads to undefined behaviour. Use std::string str = ""; to create empty strings.
std::string str = 0; resolves to the constructor std::string::string(const char* s, const Allocator& alloc = Allocator()). The behaviour of this constructor is undefined when s is nullptr. Your argument of 0 gets converted to nullptr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With