postfix evaluation using stack - c++

i'am trying to read postfix expression from txt file and evaluate it
the input is 10 5 * ,the output should be 50, but it reads only 10 and 5,
he can't read the operators neither there ascii code , any help?
here's my code
#include <iostream>
#include <iomanip>
#include <fstream>
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
#define SIZE 40
int stack[SIZE];
int top=-1;
void push(int n)
{
if(top==SIZE-1)
{
printf("Stack is full\n");
return;
}
else
{
top=top+1;
stack[top]=n;
printf("Pushed element is %d\n",n);
system("pause");
}
}
int pop()
{
int n;
if(top==-1)
{
printf("Stack is empty\n");
system("pause");
return 0;
}
else
{
n=stack[top];
top=top-1;
return(n);
}
}
int main()
{
int str[50],ch;
int i=0;
int n,op1,op2;
ifstream inFile;
ch=str[i];
inFile.open("D:\\me.txt");
if (!inFile)
{
printf( "Unable to open file");
system("pause");
exit(1); // terminate with error
}
while (inFile >> ch)
{
if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='%' || ch=='^' )
{
op1=pop();
op2=pop();
if (op1<op2)
{
n=op1;
op1=op2;
op2=n;
}
if(ch=='+')
n=op1+op2;
else if(ch=='-')
n=op1-op2;
else if(ch=='*')
n=op1*op2;
else if(ch=='/')
n=op1/op2;
else if(ch=='%')
n=op1%op2;
else if(ch=='^')
n=op1^op2;
else
{
printf("The operator is not identified\n");
system("pause");
exit(0);
}
printf("n=%d\n",n);
system("pause");
push(n);
}
else
{
n=ch;
push(n);
}
ch=str[++i];
}
inFile.close();
printf("The value of the arithmetic expression is=%d\n",pop());
system("pause");
return 0;
}

The problem is that ch is an int so inFile >> ch will only read nummbers - the '*' character is ignored.
Also, you have a str[] array which is uninitialized that you periodically read out of to assign to ch (then you ignore whatever just got written into ch). You need to get rid of str[] or complete the thought that made you put it there in the first place...

Related

C++ Stack Implementation, checking parenthesis correctness

I want to give the expression in the form of parenthesis through CIN, like: ()). then, through push & pop operation of the stack, I want the program to print me weather the given expression is BALANCED or NOT. The program works perfectly but only one issue has been found & that is when I enter like ()(, so it tells me that this expression is IMBALANCED which is fine but when I enter like () (, so then it tell me that this expression is BALANCED which is actually not balanced.
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
char Stack[10];
int top=-1;
void push(char ch)
{
if(top<10)
{
top++;
Stack[top] = ch;
}
else
cout<<"Stack Overflow";
}
void pop()
{
if(top > -1)
{
top--;
}
else
cout<<"Stack Underflow";
}
int show(){
cout<<"It is imbalanced.";
}
int main(int argc, char** argv)
{
int a=0,b=0;
string exp;
cout << "Write down the parenthesis:" ;
cin >> exp;
bool check = true;
for(int i=0; i<exp.length(); i++)
{
if(exp[i]== '(')
{
push(exp[i]);
}
else if(exp[i]== ')')
{
if(top == -1)
{
check = false;
break;
}
else
{
pop();
}
}
}
for(int i=0; i<exp.length(); i++)
{
if(exp[i]=='('){
++a;
}
else if (exp[i]==')')
{
b++;
}
}
if(a>b){
cout<<"\n\nGiven Combination is IMBALANCED";
return 0;
}
if(check == true)
cout<<"\n\nGiven Combination is BALANCED";
else
cout<<"\n\nGiven Combination is IMBALANCED";
return 0;
}
The main comments boil down to:
Don’t use a stack when no stack is needed.
And if you do use one, don’t limit it to an arbitrary fixed depth.
Handle errors and report malformed expressions.
Make sure you get the right input; std::getline() may be less error-prone than input tokenized using the >> operators. Just skip spaces (or whatever insignificant characters are allowed in the input).
using namespace std; is an antipattern and a bad habit.
The basic idea: Calculate the nesting depth as you iterate over the string. It must be zero, ultimately. It must not drop below zero at any point.
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>
using std::size_t;
bool correctly_parenthesized(std::string_view expression) {
size_t depth{0};
for (const auto character : expression) {
switch (character) {
case '(': ++depth; break;
case ')': if (depth) { --depth; break; } else { return false; }
case ' ': break;
default: throw std::invalid_argument("invalid character");
}
}
return depth == 0;
}
int main() {
std::cout << "Write down the parentheses: ";
std::string exp;
std::getline(std::cin, exp);
try {
std::cout << (correctly_parenthesized(exp) ? "YES" : "NO") << std::endl;
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
}

I have written this program for infix to postfix conversion

#include<iostream>
#include<stdio.h>
#define MAX 20
using namespace std;
char stk[MAX];
int top=-1;
void push(char c)
{
if(top==MAX-1)
cout<<"Overflow";
else
{
stk[++top]=c;
}
}
char pop()
{
if(top==-1)
{
return '\0';
}
else
return stk[top--];
}
int priority(char ch)
{
if(ch=='(')
return 1;
if(ch=='+'||ch=='-')
return 2;
if(ch=='*'||ch=='/')
return 3;
if(ch=='^')
return 4;
}
int main()
{
char exp[35],*t,x;
cout<<"Enter expression: ";
fgets(exp,35,stdin);
t=exp;
while(*t)
{
if(isalnum(*t))
cout<<*t;
else if(*t=='(')
push(*t);
else if(*t==')')
{
while((x=pop())!='(')
cout<<x;
}
else
{
if(priority(stk[top])>=priority(*t))
cout<<pop();
push(*t);
}
t++;
}
while(top!=-1)
cout<<pop();
return 0;
}
The output for input:
a+b-(c+d/e)
is
ab+cde/+
-
I don't understand why - is on a newline.
I have just started learning c++ and I am trying to implement some programs I did in c using c++. The same code in c works fine. I think there are some holes in my basic c++ knowledge and I would like to fill them up.
std::fgets does not discard the newline in the input stream like getline would. That means exp contains "a+b-(c+d/e)\n" and not "a+b-(c+d/e)". You either need to remove the newline from exp, switch to cin.getline(), or stop your processing loop when it hits the newline.
Try to change fgets to std::cin. And use std::string instead of char*:
#include <iostream>
#include <string>
int main()
{
string exp;
cout << "Enter expression: ";
std::cin >> exp;
auto t = exp.data();
char x;
for(auto &ch: exp)
{
if(isalnum(ch))
cout << ch;
else if(ch == '(')
push(ch);
else if(ch == ')')
{
while((x = pop()) != '(')
cout << x;
}
else
{
if(priority(stk[top]) >= priority(ch))
cout << pop();
push(ch);
}
}
while(top != -1)
cout << pop();
return 0;
}
In addition to the processing of '\n' as mentioned by NathanOliver, your function priority() doesn't return a value when the user entered any other character not checked in the if statements, so the behavior might be undefined.

How to make recursive function, it needs to check if in a given string the current letter and the one next to it is either lowercase or upper case?

It should convert a string like this: Example: HEloOO, should be converted into : heLOoo . For some reason it doesn't work,it just wont convert the letters from uppercase to lowercase and vice versa any help would be appreciated ?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void rek(char array[], int d)
{
int counter=0;
if(d==0)
{
printf("%s \n",array);
printf("%d \n",counter);
}
else
{
if((array[d]>='A' && array[d]<='Z')&&(array[d-1]>='A' && array[d-1]<='Z'))
{
array[d]=array[d]+32;
array[d-1]=array[d-1]+32;
counter++;
rek(array,d-2);
}
if((array[d]>='a' && array[d]<='z')&&(array[d-1]>='a' && array[d-1]<='z'))
{
array[d]=array[d]-32;
array[d-1]=array[d-1]-32;
counter++;
rek(array,d-2);
}
}
}
int main()
{
char array[100];
int d;
gets(array);
d=strlen(array);
rek(array,d);
return 0;
}
Your function does not call itself when two adjacent characters have different cases. Also you can get different results when the string is processed from the start or from the end.
I would write the function the following way
#include <stdio.h>
#include <ctype.h>
char * rek(char *s)
{
if (s[0] && s[1])
{
size_t i = 1;
if (islower((unsigned char)s[0]) && islower((unsigned char)s[1]))
{
s[0] = toupper((unsigned char)s[0]);
s[1] = toupper((unsigned char)s[1]);
++i;
}
else if (isupper((unsigned char)s[0]) && isupper((unsigned char)s[1]))
{
s[0] = tolower((unsigned char)s[0]);
s[1] = tolower((unsigned char)s[1]);
++i;
}
rek(s + i);
}
return s;
}
int main( void )
{
char s[] = "HEloOO";
puts(rek(s));
return 0;
}
The program output is
heLOoo
The main problem is that you recur only if your have a pair of upper-case or lower-case letters. Otherwise, you drop off the end of your if, return to the calling program, and quit converting things.
The initial problem is that you've indexed your string with the length. A string with 6 characters has indices 0-5, but you've started with locations 5 and 6 -- the final 'O' and the null character.
The result is that you check 'O' and '\0'; the latter isn't alphabetic at all, so you drop through all of your logic without doing anything, return to the main program, and finish.
For future reference, Here's the debugging instrumentation I used. Also see the canonical SO debug help.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void rek(char array[], int d)
{
int counter=0;
printf("ENTER rek %s %d\n", array, d);
if(d==0)
{
printf("%s \n",array);
printf("%d \n",counter);
}
else
{
printf("TRACE 1: %d %c%c\n", d, array[d-1], array[d]);
if((array[d]>='A' && array[d]<='Z')&&(array[d-1]>='A' && array[d-1]<='Z'))
{
printf("TRACE 2: upper case");
array[d]=array[d]+32;
array[d-1]=array[d-1]+32;
counter++;
rek(array,d-2);
}
if((array[d]>='a' && array[d]<='z')&&(array[d-1]>='a' && array[d-1]<='z'))
{
printf("TRACE 3: lower case");
array[d]=array[d]-32;
array[d-1]=array[d-1]-32;
counter++;
rek(array,d-2);
}
}
}
int main()
{
char *array;
int d;
array = "HEloOO";
d=strlen(array);
rek(array,d);
printf("%s\n", array);
return 0;
}
I come up with this dirty solution:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string solve(const string& str)
{
if (str.empty()) {
return "";
}
if (str.front() >= 'a' && str.front() <= 'z') {
return (char)toupper(str.front()) + solve(str.substr(1));
}
if (str.front() >= 'A' && str.front() <= 'Z') {
return (char)tolower(str.front()) + solve(str.substr(1));
}
}
int main()
{
string str;
cin >> str;
cout << solve(str) << endl;
return 0;
}

to check type of input in c++

## To check type of data entered in cpp ##
int main()
{
int num;
stack<int> numberStack;
while(1)
{
cin>>num;
if(isdigit(num))
numberStack.push(num);
else
break;
}
return(0);
}
If I declare a variable as interger, and I input an alphabet, say 'B', instead of the number, can I check this behavior of user? My code above exits when first number is entered and does not wait for more inputs.
First of all, the std::isdigit function checks if a character is a digit.
Secondly, by using the input operator >> you will make sure that the input is a number, or a state flag will be set in the std::cin object. Therefore do e.g.
while (std::cin >> num)
numberStack.push(num);
The loop will then end if there's an error, end of file, or you input something that is not a valid int.
First take your input as string
Using builtin libraries like isdigit() classify it as an integer
else if it contains '.'then its a float
else if it a alphanumerical the it is a string thats it
Code for this is below,
#include<iostream>
#include<string.h>
using namespace std;
int isint(char a[])
{
int len=strlen(a);
int minus=0;
int dsum=0;
for(int i=0;i<len;i++)
{
if(isdigit(a[i])!=0)
dsum++;
else if(a[i]=='-')
minus++;
}
if(dsum+minus==len)
return 1;
else
return 0;
}
int isfloat(char a[])
{
int len=strlen(a);
int dsum=0;
int dot=0;
int minus=0;
for(int i=0;i<len;i++)
{
if(isdigit(a[i])!=0)
{
dsum++;
}
else if(a[i]=='.')
{
dot++;
}
else if(a[i]=='-')
{
minus++;
}
}
if(dsum+dot+minus==len)
return 1;
else
return 0;
}
int main()
{
char a[100];
cin>>a;
if(isint(a)==1)
{
cout<<"This input is of type Integer";
}
else if(isfloat(a)==1)
{
cout<<"This input is of type Float";
}
else
{
cout<<"This input is of type String";
}
}
use cin.fail() to check error and clean the input buffer.
int num;
while (1) {
cin >> num;
if (cin.fail()) {
cin.clear();
cin.sync();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if (num == -1) {
break;
}
numberStack.push(num);
}

how to print out more than a character at once

I saved this word "abs" in a text file and i'm trying to make a code that can print the three characters at once in another file .. not like that
while (content[i] == 'a')
{
fout<<"a";
break;}
while (content[i] == 'b')
{
fout<<"b";
break;}
while (content[i] == 's')
{
fout<<"s";
break;}
here is the code i wrote but it doesn't print anything out..
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout("E:\\hoss.txt");
ifstream file("E:\\test.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
while (content[i] == 'ab')
{
fout<<"ab";
break;}
}}
system("pause");
return 0;
}
anyone can help??
int main()
{
ofstream fout("E:\\hoss.txt");
ifstream file("E:\\test.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
if((content[i] == 'a') && (content[i+1] == 'b'))
{
fout<<"ab";
break;
}
}
}
system("pause");
return 0;
}
You have no code to print anything out. You just keep adding to the buffer, but you never flush the buffer. Get rid of the system("pause"); and just let the program end. Ending the program flushes all buffers.
while (content[i] == 'ab')
This is pretty baffling. Did you really mean ab as a character constant?