g++ saying function doesn't exist even when including the proper header - c++

So I am working on some homework for my uni and need to convert a string to a float. For whatever reason g++ is complaining that the 'stof' function doesn't exist. Although I have included the required header. Here is my code, the error is on the line that says
holder = stof(x.substr(0, end_of_num));
#include <iostream>
#include <string>
#include <list>
using namespace std;
float process_func(string x);
bool isPartOfNum(char x);
int main() {
string x;
while (true) {
cout << "input a string" << endl;
getline(cin, x);
cout << process_func(x);
}
return 0;
}
float process_func(string x) {
int end_of_num =0;// used to find last index from num
int negMult = 1; //used to multiply value at end if there was a negative
bool onNum = false; //used to
list <float> numList;
list <char> operList;
if ((x.at(0) < 48 || x.at(0) > 57) && x.at(0) != '-') //check if start of string doesnt have a number or negative symbol
return -1;
if (x.at(0) != '-')
negMult = -1;
float holder;// temp holder for floats
int i = 0;
while (i<x.length()) {
if (isPartOfNum(x.at(i))) {
end_of_num++;
onNum = true;
}
else if (onNum) {
holder = stof(x.substr(0, end_of_num));
numList.push_back(holder); //adds num as float to list
x.erase(0, end_of_num + 1); //+1 removes the space after the number before the operator
end_of_num = 0;
onNum = false;
}
if (x.at(i) == '+' || x.at(i) == '-' || x.at(i) == '*' || x.at(i) == '/') {
operList.push_back(x.at(i));
}
} //at this point both lists should be full of all needed pieces of info
int answer = 0;
int temp;
bool firstOper=true; // used to hold first operation
while (numList.size() >=2) { //requires at least 2 entries for last operation
while (!operList.empty()) {
temp = numList.front();
numList.pop_front();
if (operList.front() == '+') {
if (firstOper) {
answer = temp + numList.front();
numList.pop_front();
firstOper = false;
}
else {
answer += temp;
}
}
else if (operList.front() == '-') {
if (firstOper) {
answer = temp - numList.front();
numList.pop_front();
firstOper = false;
}
else {
answer -= temp;
}
}
else if (operList.front() == '*') {
if (firstOper) {
answer = temp * numList.front();
numList.pop_front();
firstOper = false;
}
else {
answer *= temp;
}
}
else if (operList.front() == '/') {
if (firstOper) {
answer = temp / numList.front();
numList.pop_front();
firstOper = false;
}
else {
answer /= temp;
}
}
operList.pop_front();
}
}
return answer;
}
bool isPartOfNum(char x) {
if ((x >= 48 && x <= 57) || (x == '-' || x == '.'))
return true;
return false;
}

Solved by compiling using c++ 11

Related

Backspace String Compare given two strings s and t, return true if they are equal

I am getting a runtime error for this test case using stack
"bxj##tw", "bxj###tw"
Line 171: Char 16: runtime error: reference binding to misaligned address 0xbebebebebebec0ba for type 'int', which requires 4 byte alignment (stl_deque.h)
0xbebebebebebec0ba: note: pointer points here
<memory cannot be printed>
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_deque.h:180:16
class Solution {
public:
bool backspaceCompare(string s, string t) {
stack<int>st1;
stack<int>st2;
for(int i=0; i<s.size(); i++){
if(st1.empty() && s[i]!='#'){
st1.push(s[i]);
}
else{
if(!st1.empty() && s[i]=='#'){
st1.pop();
}
else if(s[i]=='#' && (st1.empty())){
continue;
}
else{
st1.push(s[i]);
}
}
}
for(int i=0; i < t.size(); i++){
if(st2.empty() && t[i]!='#'){
st2.push(t[i]);
}
else{
if(!st2.empty() && t[i]=='#'){
st2.pop();
}
else if(t[i]=='#' && st2.empty()){
continue;
}
else{
st2.push(t[i]);
}
}
}
if(st1.empty() && st2.empty()){
return "";
}
while(!st1.empty()){
if(st1.top()!= st2.top()){
return false;
}
else{
st1.pop();
st2.pop();
}
}
return true;
}
};
I wouldn't use a stack<char> since the natural representation is a string, and you're not using any functionality of the stack's ability to expand or shrink in the front (other than the end where you can just say return a == b). string has push_back and pop_back methods as well.
For small input (like the ones guaranteed for this challenge problem), I'd recommend constructing the two "editors" and comparing with ==:
class Solution {
public:
bool backspaceCompare(string s, string t) {
return backspace(s) == backspace(t);
}
private:
string backspace(const string &s) {
string editor = "";
string::const_iterator commandItr = s.cbegin();
while(commandItr != s.cend())
if(*commandItr == '#' && !editor.empty()) {
editor.pop_back();
++commandItr;
} else if(*commandItr != '#')
editor.push_back(*commandItr++);
else
++commandItr;
return editor;
}
};
However, they did challenge the coder to use O(1) memory. Here is an example of that:
class Solution {
public:
bool backspaceCompare(string s, string t) {
int left = s.size() - 1;
int right = t.size() - 1;
while(true) {
left = backspace(s, left);
right = backspace(t, right);
if (left == -1 && right == -1)
return true;
if (left == -1 && right != -1 || right == -1 && left != -1)
return false;
if(s[left--] != t[right--])
return false;
}
}
private:
// Returns first index from back that indexes to a non-deleted character
int backspace(string const &s, int startingIndex) {
if(startingIndex == -1)
return -1;
if(s[startingIndex] != '#')
return startingIndex;
unsigned backspaceCount = 0;
while(true) {
while(startingIndex != -1 && s[startingIndex] == '#') {
++backspaceCount;
--startingIndex;
}
while (startingIndex != -1 && backspaceCount && s[startingIndex] != '#') {
--startingIndex;
--backspaceCount;
}
if (startingIndex == -1)
return -1;
else if(s[startingIndex] != '#' && !backspaceCount)
return startingIndex;
}
}
};

Infix to Postfix using Stacks w/ Professor's Algorithm

Been scratching my head for hours already and I have no clue what my mistake is. I'm following my professor's derived algorithm step by step and I don't know why it isn't working properly.
Here's the derived Algorithm:
Here's the code that I tried to make:
#include <iostream>
#include "ecpe202.h"
#define Max 100
using namespace std;
int getICP(char x){
if (x == ')'){
return 0;
}
else if (x == '^'){
return 4;
}
else if (x == '*' || x == '/'){
return 2;
}
else if (x == '+' || x == '-'){
return 1;
}
else if (x == '('){
return 4;
}
}
int getISP(char x){
if (x == ')'){
return 0;
}
else if (x == '^'){
return 3;
}
else if (x == '*' || x == '/'){
return 2;
}
else if (x == '+' || x == '-'){
return 1;
}
else if (x == '('){
return 0;
}
}
bool isOperator(char ch){
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' || ch == '*' || ch == '(' || ch == ')'){
return (true);
}
else{
return (false);
}
}
int main(){
char infix[Max];
char ch;
int length;
myQueue que;
myStack stk;
createQ(que);
createS(stk);
cout << "Enter an infix Expression: ";
cin >> infix;
cout << endl << endl;
cout << "The postfix Expression: ";
length = strlen(infix);
for (int i = 0; i < length; i++){
addQ(que, infix[i]);
}
while (!isEmptyQ(que)){
ch = retrieveQ(que);
//start of infix to postfix algo
//1. push
if (ch == '('){
pushS(stk, ch);
}
//2. if scanned is operand
if (!isOperator(ch)){
cout << ch;
}
else{
//2.1 push if...
if (isEmptyS(stk) || getICP(ch) > getISP(topS(stk)) || topS(stk) == '('){
pushS(stk, ch);
}
//2.2. pop all operators
else{
while(!isEmptyS(stk) && getISP(topS(stk)) >= getICP(ch) || topS(stk) == '('){
cout << popS(stk);
}
}
pushS(stk, ch);
}
//3. If scanned ')'
bool loop = true;
if (ch == ')'){
do{
if (ch == '('){
loop = false;
}
else{
cout << popS(stk);
}
}while(loop == true);
}
//repeat 1-3
}
cout << endl;
}
For the ecpe202.h:
#include<dos.h>
#include<windows.h>
#define FOREVER true
#define MAXSTACK 100
#define MAXQUEUE 100
using namespace std;
struct myStack{
int tos;
char s[MAXSTACK];
};
struct myQueue{
int head, tail, q[MAXQUEUE];
};
//STACK
void createS(myStack &S){
S.tos=-1;
}
void pushS(myStack &S, char item){
S.s[++S.tos] = item;
}
char popS(myStack &S){
return(S.s[S.tos--]);
}
char topS(myStack S){
return (S.s[S.tos]);
}
bool isFullS(myStack S){
if(S.tos == MAXSTACK - 1)
return true;
return false;
}
bool isEmptyS(myStack S){
if (S.tos == -1)
return true;
return false;
}
//QUEUE
void createQ(myQueue &Q){
Q.head = 0;
Q.tail = 0;
}
void addQ(myQueue &Q, char item){
Q.q[Q.tail++] = item;
Q.tail %= MAXQUEUE;
}
char retrieveQ(myQueue &Q){
char temp;
temp = Q.q[Q.head++];
Q.head %= MAXQUEUE;
return temp;
}
bool isFullQ(myQueue Q){
if (Q.tail == MAXQUEUE)
return true;
return false;
}
bool isEmptyQ(myQueue Q){
if (Q.tail == Q.head)
return true;
return false;
}
//GOTOXY
void gotoxy(int x, int y){
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void clrscr(){
system("CLS");
}
The output that my code:
What seems to be wrong in my program? tried re-reading it a couple of times and I still can't fix it.

How to fix runtime error in Shunting Yard algorithm

I have implemented Shunting yard algorithm using stack in c++.
Well it is working quite well on inputs from SPOJ example inputs but when I input:
1
(((a+b) * (c+r)^(t+b)-n)^(c-(d * e))-b)+(c+(e-(d^r)))
I get a runtime error.
Note: I only get a runtime error when I call infixToPostfix() and use the above input and not when I comment it out.
Submission to SPOJ and running on ideone(with input above) results in a runtime error.
I really can't understand this behaviour of my program, so any help is welcomed.
I have tried some random inputs and it seems to work fine on them.
Even though they had spaces around operators.
#include<iostream>
#include<vector>
#include<math.h>
#include<stack>
#include<strings.h>
using namespace std;
void infixToPostfix(string st);
int pr(char s);
int main() {
int t;
scanf("%d",&t);
cin.ignore();
string st; // input string
while(t--)
{
getline(cin,st);
cin.sync();
cout<<st<<endl;
infixToPostfix(st);
}
return 0;
}
int pr(char s) // to check precedence
{
if(s == '^')
{
return 4;
}
else if(s == '*')
{
return 3;
}
else if(s == '/')
{
return 3;
}
else if(s == '+')
{
return 2;
}
else if(s == '-')
{
return 2;
}
else {
return 0;
}
}
void infixToPostfix(string st)
{
stack<char>op; //stack to hold operators and bracket
st += 'n';
int l = st.size();
op.push('0');
string fst; //final string
for(int x = 0;x<l;x++)
{
if(st[x] == '(')
{
op.push(st[x]);
}
else if(st[x] == ')')
{
while(op.top() != '(' && !op.empty())
{
fst +=op.top();
op.pop();
}
op.pop();
}
else if(st[x] == '+' || st[x] == '-' || st[x] == '*' ||st[x] == '/' ||st[x] == '^')
{
if(pr(st[x]) <= pr(op.top()))
{
fst += op.top();
op.pop();
op.push(st[x]);
}
else{
op.push(st[x]);
}
}
else if(st[x] == 'n'){
while(op.size() != 0)
{
if(op.top() != '0')
{fst += op.top();}
op.pop();
}
}
else if((st[x] >= 'a' || st[x] <= 'z' )&& st[x] != ' ')
{
fst += st[x];
}
}
printf("%s\n",fst.c_str());
}

Seg Fault with Prefix

I am getting a segmentation fault when trying to convert an infix expression into prefix order. I have a postfix using the same logic that works fine the issue seems to be where i try to read the infix expression in reverse but I am not exactly sure why it is faulting. Any help would greatly appreciated Here is the relevant code:
int ParseTree::prefix(string infix)
{
vector<string> exp;
stringstream ss(infix);
string tok;
while(getline(ss,tok,' '))
{
exp.push_back(tok);
}
vector<string> prefix;
stack<string> s;
for(unsigned int i = exp.size() - 1; i >= 0 ; i--)
{
if(parseTry(exp[i]))
{
prefix.push_back(exp[i]);
}
if(exp[i] == "(")
{
s.push(exp[i]);
}
if(exp[i] == ")")
{
while(!s.empty() && s.top() != "(")
{
prefix.push_back(s.top());
s.pop();
}
s.pop();
}
if(isOperator(exp[i]) == true)
{
while(!s.empty() && priority(s.top()) >= priority(exp[i]))
{
prefix.push_back(s.top());
s.pop();
}
s.push(exp[i]);
}
}
while(!s.empty())
{
prefix.push_back(s.top());
s.pop();
}
for(unsigned int i = 0; i < prefix.size(); i++)
{
cout << prefix[i] << " ";
}
return 0;
}
int ParseTree::priority(const string &s)
{
if(s == "*" || s == "/")
{
return 2;
}
if(s == "+" || s == "-")
{
return 1;
}
else
{
return 0;
}
}
bool ParseTree::parseTry(const string &s)
{
bool number = false;
for(unsigned int i = 0; i < s.size(); i++)
{
if(!isdigit(s[i]))
{
number = false;
}
else
{
number = true;
}
}
return number;
}
bool ParseTree::isOperator(const string &s)
{
return (s == "+" || s == "-" || s == "*" || s == "/");
}

C++ Infix to Postfix program, Stack is continuously empty?

I'm working on a program for a computer science class. I have everything completed and separated into the interface/implementation and for some reason, the program loops infinitely and says "Stack is empty!" after the peek() function is called.
I've tried inserting cout << statements to see if I can pinpoint the issue, however, no luck. I would appreciate it if someone else could take a look at it.
Thank You
Header
#ifndef STACK_H
#define STACK_H
/////////////////////////////////////////////////////
////Includes/////////////////////////////////////////
/////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdlib.h>
#include <iomanip>
#include <sstream>
#include <stdio.h>
/////////////////////////////////////////////////////
using namespace std;
/*-------------------------------------------------------------------------------------------------------------*/
template <typename Object>
class Stack
{
private:
class stackListNode
{
public:
Object data;
stackListNode *next;
private:
//Nothing to declare-->placeholder since class
//sets data members to private initially
};
stackListNode *top;
public:
/////////////////////////////////////////////////
//Constructor Function//////////////////////////
Stack() {top = NULL;}
/////////////////////////////////////////////////
//Rest of functions defined inline for simplicity
void push(char token) // Push token onto the stack and create new node for top of stack
{
stackListNode *newNode = new stackListNode;
newNode->data = token;
newNode->next = top;
top = newNode;
}
int pop()
{
if(empty())
{
cout << "Stack is empty!\n" << endl;
return NULL;
}
stackListNode *temp = top;
top = temp->next;
}
char peek()
{
if(empty())
{
cout << "Stack is empty!\n" << endl;
return NULL;
}
return top->data;
}
int empty()
{
return top == NULL;
}
};
#endif
Main File:
/////////////////////////////////////////////////////
////Includes/////////////////////////////////////////
/////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <string>
#include "Stack.h"
/////////////////////////////////////////////////////
using namespace std;
int precendence(char stack_beginning); //ensures order of operations.
int precendence(char*myArray);
void InFixToPostfix(ifstream& in_file);
double EvaluatePostfix(double first_operand, double second_operand, char*myArray);
int main()
{
////VARS/////////////////////////////////////////////
string absolutePath;
cout << endl;
cout << "Please type in the name of the file you would to open \n";
cin >> absolutePath;
ifstream in_file;
in_file.open(absolutePath.c_str());
if(!in_file)
{
cout << "failed to open input file\n" ;
return 1 ;
}
else
{
InFixToPostfix(in_file); //kicks off program
}
}
void InFixToPostfix(ifstream& in_file)
{
string infix;
int right_parentheses =0;
int left_parentheses =0;
while(getline(in_file, infix))
{
char myArray[infix.size()];
strcpy(myArray, infix.c_str());
for(int i = 0; i < sizeof(myArray); i++)
{
if(myArray[i] == '(')
{
right_parentheses++;
}
if(myArray[i] == ')')
{
left_parentheses++;
}
}
if(right_parentheses!=left_parentheses)
{
cout << endl;
cout << "There is a typo in one of the expressions in your file \n";
cout << "Please fix it and rerun the program \n";
exit(1);
}
for(int i = 0; i < sizeof(myArray); i++)
{
//int number = int(myArray[i]);
//deferences the pointer and reads each char in the array
//as an int rather than a character.
//int number = myArray[i];
if(isxdigit(myArray[i]) > 0) //function used to check for hexidecimal values (i.e. int's)
{
goto exit_out;
}
else if(myArray[i] == '(' || myArray[i] == ')' || myArray[i] == '+' || myArray[i] == '-' || myArray[i] == '*' || myArray[i] == '/' || myArray[i] == '\\' || myArray[i] == '\n')
{
goto exit_out;
}
else if(myArray[i] == char(32)) //checks to see if there is a space
{
goto exit_out;
}
else
{
cout << endl;
cout << "There is an invalid character in the file\n";
exit(1);
}
exit_out:;
}
////////Declares a STRING Stack////////////////////////////////
Stack<char> stack_string;
////////Declares an Int Stack/////////////////////////////////
Stack<int> stack_int;
//////////////////////////////////////////////////////////////
for(int i = 0; i < sizeof(myArray); i++)
{
int number = isxdigit(myArray[i]);
if(number > 0)
{
cout << number;
//outputs the number b/c it is an operand
}
if(myArray[i] == '(')
{
stack_string.push(myArray[i]);
}
if(myArray[i] == ')')
{
//cout << "test";
while(stack_string.peek() != '(')
{
cout << stack_string.peek();
stack_string.pop(); //pops to the peek
}
stack_string.pop(); // if there is a ), pops to the peek
}
if(myArray[i] == '+' || myArray[i] == '-' || myArray[i] == '/' || myArray[i] == '*')
{
if(stack_string.empty())
{
stack_string.push(myArray[i]); //if there's nothing on the stack, pushes the current character
//goto done;
break; //breaks out of the statement
}
char stack_beginning = stack_string.peek();
int stack_top = precendence(stack_beginning);
//int stack_top = precendence(stack_string.peek());
int operatorHierarchy = precendence(myArray);
//must be declared here because i will have been interated through array
if(operatorHierarchy > stack_top)
{
stack_string.push(myArray[i]);
}
else if(operatorHierarchy <= stack_top) //could also be an if
{
dump_out:;
cout << stack_string.peek();
stack_string.pop();
int rerunThroughStack =0;
char new_stack_beginning = stack_string.peek();
rerunThroughStack = precendence(new_stack_beginning);
if(operatorHierarchy < stack_top)
{
stack_string.push(myArray[i]);
goto done; //could break
}
if(stack_string.peek() == '(')
{
stack_string.push(myArray[i]);
goto done;
}
if(stack_string.empty())
{
stack_string.push(myArray[i]);
goto done;
}
goto dump_out;
}
}
done:;
}
cout << stack_string.peek() << endl;
//////////Evaluate Section/////////////////////////////
for(int i = 0; i < sizeof(myArray); i++)
{
if(isxdigit(myArray[i]) > 0) //this is a number
{
stack_int.push(isxdigit(myArray[i]));
goto end;
}
else if(myArray[i] == '*' || myArray[i] == '+' || myArray[i] == '-' || myArray[i] == '/')
{
double first_operand;
first_operand = stack_int.peek(); //fetches first operand on the stack_int
stack_int.pop();
//////////////////
double second_operand;
second_operand = stack_int.peek();
stack_int.pop();
//////////////////
double answer;
answer = EvaluatePostfix(first_operand, second_operand, myArray); //THIS PROBABLY IS NOT RIGHT
stack_int.push(answer);
}
end:;
}
/*
int size_of_stack;
size_of_stack = stack_int.size();
if(size_of_stack == 1)
{
cout << stack_int.peek();
}
*/
}
}
double EvaluatePostfix(double first_operand, double second_operand, char* myArray) //might have to pass array as reference
{
/*
Cycle through the characters passed in through myArray[i];
*/
for(int i = 0; i < sizeof(myArray); i++)
{
if(myArray[i] == '*')
{
double first_answer;
first_answer = (second_operand * first_operand);
return first_answer;
}
else if(myArray[i] == '/')
{
double second_answer;
second_answer = (second_operand / first_operand);
return second_answer;
}
else if(myArray[i] == '+')
{
double third_answer;
third_answer = (second_operand + first_operand);
return third_answer;
}
else if(myArray[i] == '-')
{
double fourth_answer;
fourth_answer = (second_operand - first_operand);
return fourth_answer;
}
/*
else
{
cout << "There must be an error in your file" <<endl;
break;
exit(1);
}
*/
}
}
int precendence(char stack_beginning)
{
int precendence;
if(stack_beginning == '*' || stack_beginning == '/')
{
precendence = 2;
return precendence;
}
//by making it 2, the precendence is dubbed less than +/-
if(stack_beginning == '+' || stack_beginning == '-')
{
precendence = 1;
return precendence;
}
} //by making it 1, the precendence is dubbed greater than */"/"
int precendence(char*myArray)
{
int precendence;
for(int i = 0; i < sizeof(myArray); i++)
{
if(myArray[i] == '*' || myArray[i] == '/')
{
precendence = 2;
return precendence;
}
//by making it 2, the precendence is dubbed less than +/-
if(myArray[i] == '+' || myArray[i] == '-')
{
precendence = 1;
return precendence;
}
} //by making it 1, the precendence is dubbed greater than */"/"
}