Prefix to Infix? - c++

In my class one of our assignments is to convert a prefix equation to infix. After reading that section I still have no idea what I'm doing. The book had some code that will solve a prefix equation when given but I have no idea how it does it or how I would display the infix version. Any help would be appreciated in explaining how this code finds the solution and how I could have it display a infix version.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int prefixExpr(istream &exprStream);
int main() {
string input;
cout << "Enter prefix expressions to evaluate. \nPress enter after each expression, and press enter on a blank line to quit." << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
while (input.size() != 0){
istringstream exprStream(input);
cout << prefixExpr(exprStream) << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
}
return 0;
}
int prefixExpr(istream &exprStream) {
char ch = exprStream.peek();
while (isspace(ch)) {
ch = exprStream.get();
ch = exprStream.peek();
}
cout << ch << endl;
if (isdigit(ch)) {
int number;
exprStream >> number;
cout << number << endl;
return number;
}
else {
ch = exprStream.get();
int value1 = prefixExpr(exprStream);
int value2 = prefixExpr(exprStream);
switch (ch) {
case '+': return value1 + value2;
case '-': return value1 - value2;
case '*': return value1 * value2;
case '/': return value1 / value2;
default: cout << "Bad input expression";
exit(1);
}
}
}

Related

How to add characters from a file that are not evenly spaced?

I'm taking C++ for the first time. And I'm a bit stuck on the final entry calculation.
5+6- 7 -8 + 9 + 10 - 11;
The question deliberately spaces things out of order and I don't know how to account for it. Any help on this would be amazing as I don't know what I'm missing. Thank you so much!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int val;
while (cin >> val)
{
string op;
while (cin >> op)
{
if (op == ";")
{
cout << val << endl;
break;
}
int num;
if (! (cin >> num)) {
cout << "a number is expected after '" << op << '\'' << endl;
return -1;
}
if (op == "+")
{
val += num;
}
else if (op == "-")
{
val -= num;
}
else {
cout <<"invalid operator '" << op << '\'' << endl;
return -1;
}
}
}
return 0;
}
You can do like following. See it working here:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int val;
int num;
char op;
bool isNotStop(true);
cin>>val;
while (isNotStop)
{
cin.get(op);
//cout<<"Craracter is: ["<<op << "]"<<endl;
if(isspace(op)) continue;
switch(op)
{
case '+':
if (!(cin >> num))
{
cout << "a number is expected after '" << op << '\'' << endl;
return -1;
}
val += num;
break;
case '-':
if (!(cin >> num))
{
cout << "a number is expected after '" << op << '\'' << endl;
return -1;
}
val -= num;
break;
break;
case ';':
isNotStop = false;
break;
default:
{
cout <<"invalid operator '" << op << '\'' << endl;
return -1;
}
}
}
cout<<"Result: "<<val;
return 0;
}
I'm new here and this is my first attempt at answering a question. This might not be the best way to do it.
I think you should read the whole thing in a string with getline(cin, string), then go through the string with a for loop and get rid of all spaces. Then you can define a string stream from the resulting string and use it instead of cin.
It will look something like this:
string s1,s2;
getline(cin, s1);
for (int i = 0; i < s1.length(); i++) {
if (s1[i] != ' ')
s2 += s1[i];
}
stringstream ss;
ss << s2;
and from now on use ss instead of cin.
just make sure to include sstream and string headers.

Why do I get infinite loop instead of exception?

I make a program which will have some functions to work with my structure. I haven't added the functions yet, but I have problems with user interface. When I input "hello" instead of int (for choice & choice2), I expect to get exception but instead I get infinite loop. If "hello" is an array of chars and chars are transferred to corresponding ASCII codes, I don't understand why loop is infinite. I need exception so I can catch it.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define MARK_AMOUNT 4
struct student{
string name;
string group;
int mark[MARK_AMOUNT];
};
istream& operator >> (istream& in, student& student) {
in >> student.name >> student.group;
for (int i = 0; i < MARK_AMOUNT; i++) in >> student.mark[i];
return in;
}
ostream& operator << (ostream& out, const student& student) {
out << student.name << "\t" << student.group << "\t";
for (int i = 0; i < MARK_AMOUNT; i++) out << student.mark[i] << " ";
return out;
}
int main(){
vector <student> list;
int choice, choice2;
ifstream myfile;
bool input = false, input2 = false;
while(!input){
cout << "Input:\n1 to work with files\n2 to work in console\n";
cin >> choice;
if(choice == 1 || choice == 2) input = true;
else cout << "Wrong number.\n";
}
while(!input2){
cout << "Input function number[1-3]: ";
cin >> choice2;
if(choice2 >= 1 && choice2 <= 3) input = true;
else cout << "Wrong number.\n";
}
switch (choice) {
case 1:
{
string fileName;
cout << "Input name of file: ";
cin >> fileName;
ifstream myfile(fileName);
student temp;
while(myfile >> temp){
list.push_back(temp);
}
}
break;
case 2:
break;
default:
break;
}
switch (choice2) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
switch (choice) {
case 1:
{
myfile.close();
break;
}
case 2:
break;
default:
break;
}
return 0;
}
Output:
Input:
1 to work with files
2 to work in console
hello
Wrong number.
Input:
1 to work with files
2 to work in console
Wrong number.
Input:
1 to work with files
2 to work in console
Wrong number.
...
...
If you want execution to continue then you definitely do not need an exception.
You need a mechanism to first check if the input is valid since std::cin goes into an error state and leaves the input in its buffer, thus skipping through the next call.
Here is the sample on wich you can build upon:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
int choice, choice2;
bool input = false, input2 = false;
std::string line;
while(!input){
cout << "Input:\n1 to work with files\n2 to work in console" << endl;
while (std::getline(std::cin, line))
{
std::stringstream ss(line);
if (ss >> choice)
{
if (ss.eof())
{ // Success
break;
}
}
std::cout << "Invalid Input, try again" << endl;
}
if(choice == 1 || choice == 2) input = true;
else {
cout << "Wrong number.\n" << endl;
}
}
}

How to make a calculator in c++ using if else and functions?

I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }

C++ error when running code

I'm trying to learn C++ and i cant figure a problem out.
My code:
#include <iostream>
using namespace std;
int userContinue = true;
int userContinueString;
int getUserInput() {
int userInput1;
int userInput2;
cout << "Please enter your first number: ";
cin >> userInput1;
cout << endl << "Please enter your second number: ";
cin >> userInput2;
cout << endl << "The result of the two numbers together: " << userInput1+userInput2;
userInput1 = 0;
userInput2 = 0;
return 0;
}
int main()
{
while (userContinue == true) {
getUserInput();
cout << endl << "Would you like to continue? (Y/N): ";
cin >> userContinueString;
if (userContinueString ='Y') {
}
else {
userContinue = false;
}
}
return 0;
}
The code works fine until i input "Y" ant then it keeps looping as shown here: Video
First, make sure you compile your code with some warning switches such as -Wall -Wpedantic. These switches will help you. For instance, in your original code, my compiler prints the following warnings:
prog.cpp:25:28: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (userContinueString = 'Y') {
~~~~~~~~~~~~~~~~~~~^~~~~
prog.cpp:25:28: note: place parentheses around the assignment to silence this warning
if (userContinueString = 'Y') {
^
( )
prog.cpp:25:28: note: use '==' to turn this assignment into an equality comparison
if (userContinueString = 'Y') {
^
==
1 warning generated.
Then, I fix the corresponding line with ==, which was already suggested in the comments. Then, your comparison should be case-insensitive. Finally, you would like to compare character objects with respect to 'y' or 'Y':
#include <cctype>
#include <iostream>
using namespace std;
int userContinue = true;
char /* not int */ userContinueString;
int getUserInput() {
int userInput1;
int userInput2;
cout << "Please enter your first number: ";
cin >> userInput1;
cout << endl << "Please enter your second number: ";
cin >> userInput2;
cout << endl
<< "The result of the two numbers together: " << userInput1 + userInput2;
userInput1 = 0;
userInput2 = 0;
return 0;
}
int main() {
while (userContinue == true) {
getUserInput();
cout << endl << "Would you like to continue? (Y/N): ";
cin >> userContinueString;
if (std::tolower(userContinueString) == 'y') {
} else {
userContinue = false;
}
}
return 0;
}
EDIT. I have improved the answer by taking into account David's comment below. Note the use of #include <cctype> and std::tolower.
EDIT. I have tried improving the answer further by trying to address the "learning C++" comment below:
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
template <class value_t,
typename std::enable_if<std::is_floating_point<value_t>::value,
int>::type = 0>
struct Calculator {
Calculator() = default;
explicit operator bool() {
while (true) {
std::cout << "Valid operations: +, -, *, /, 0 (exit)\n";
std::cout << "What would you like to do: ";
if (!getUserInput(operation)) {
std::cerr << "Wrong input for operation\n";
continue;
}
switch (operation) {
case '0':
return false;
case '+':
case '-':
case '*':
case '/':
break;
default:
std::cerr << "Wrong input for operation\n";
continue;
}
std::cout << "Please enter v1: ";
if (!getUserInput(v1)) {
std::cerr << "Wrong input for v1\n";
continue;
}
std::cout << "Please enter v2: ";
if (!getUserInput(v2)) {
std::cerr << "Wrong input for v2\n";
continue;
}
calculate();
return true;
}
}
friend std::ostream &operator<<(std::ostream &os, const Calculator &c) {
os << "v1 " << c.operation << " v2 = " << c.result;
return os;
}
private:
char operation;
value_t v1, v2, result;
std::string line;
void calculate() {
switch (operation) {
case '+':
return calculate(std::plus<value_t>{});
case '-':
return calculate(std::minus<value_t>{});
case '*':
return calculate(std::multiplies<value_t>{});
case '/':
return calculate(std::divides<value_t>{});
case '0':
return;
}
}
template <class Func> void calculate(Func &&f) { result = f(v1, v2); }
template <class T> bool getUserInput(T &t) {
std::cin >> line;
std::istringstream ss{line};
return (ss >> t) && (ss >> std::ws).eof();
}
};
int main() {
Calculator<double> c;
while (c)
std::cout << c << '\n';
return 0;
}

How to clear the previous input in c++?

'cause my program joins the previous input to my current input. I want to clear the previous input.
This is the code:
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int ini=1,an=1,ans=1, f=1;
int bb=2;
int hypin;
string a="a.) Hyperfactorial";
string b="b.) Superfactorial";
string c="c.) Primorials";
string d="Exit";
string e="a. Yes";
string ff="b. No";
string letter;
string ysno;
start:
cout<<"\n"<<"Factorial"<<"\n"<<a<<"\n"<<b<<"\n"<<c<<endl;
cout<<"\n"<<"Enter letter:"<<endl;
cin>>letter;
if (letter=="a"){
cout<<"\n"<<"Enter number (maximum input:7) : "<<endl;
cin>>hypin;
if(hypin>=8){
cout<<"\n"<<"Invalid input!"<<endl;
}else{
while (hypin>1){
ini=ini*(pow(hypin,hypin));
hypin--;
}
cout<<"\n"<<"The hyperfactorial is: "<<ini<<endl;}
cout<<"\n"<<"Do you want to test another factorial?"<<"\n"<<e<<"\n"<<ff<<endl;
cout<<"\n"<<"Answer: ";
cin>>ysno;
if(ysno=="a"){
goto start;
}
if(ysno=="b"){
cout<<"\n"<<"Press any key to exit"<<"\n"<<endl;
getch();
return 0;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
Try clearing the cin buffer using
std::cin.ignore(INT_MAX);
Edit: You have to #include <limits.h> to use INT_MAX
You don't need to clear any thing. infact you have some little bug in your code that not set the answer every time.
I try to write a simple code for you:
bool validInput = false ,continueFlag = true;
string opr, ysno;
int a , b, ans = 0;
while(continueFlag)
{
cout << "Choose operation: a. Multiply b. Add \n Enter letter: " << endl;
cin >> opr;
if (opr != "a" && opr != "b")
{
cout << "Invalid input!"<<endl;
continue; // it returns to "while(continueFlag)" line
}
cout << "Enter First Number: ";
cin >> a;
cout << "Enter Second Number: ";
cin >> b;
if (opr == "a")
{
ans = a * b;
}
else
{
ans = a + b;
}
cout << "Answer is : "<< ans << endl;
do
{
cout << "Do you want to test another factorial? a. Yes b. No" << endl;
cin >> ysno;
if (opr != "a" && opr != "b")
{
cout << "Invalid input!"<<endl;
continue; // it returns to "do" line
}
validInput = true;
if (ysno == "b")
{
continueFlag = false;
}
}while(!validInput);
}
try this might be helpful
cout << "\033[2J\033[1;1H";
I used this code and compiled with g++ its working and linux platfrom(ubuntu)
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int ini=1,an=1,ans=1, f=1;
int bb=2;
int hypin;
string a="a.) Hyperfactorial";
string b="b.) Superfactorial";
string c="c.) Primorials";
string d="Exit";
string e="a. Yes";
string ff="b. No";
string letter;
string ysno;
start:
cout<<"\n"<<"Factorial"<<"\n"<<a<<"\n"<<b<<"\n"<<c<<endl;
cout<<"\n"<<"Enter letter:"<<endl;
cin>>letter;
if (letter=="a"){
cout<<"\n"<<"Enter number (maximum input:7) : "<<endl;
cin>>hypin;
cout << "\033[2J\033[1;1H";
if(hypin>=8){
cout<<"\n"<<"Invalid input!"<<endl;
}else{
while (hypin>1){
ini=ini*(pow(hypin,hypin));
hypin--;
}
cout<<"\n"<<"The hyperfactorial is: "<<ini<<endl;}
cout<<"\n"<<"Do you want to test another factorial?"<<"\n"<<e<<"\n"<<ff<<endl;
cout<<"\n"<<"Answer: ";
cin>>ysno;
if(ysno=="a"){
goto start;
}
if(ysno=="b"){
cout<<"\n"<<"Press any key to exit"<<"\n"<<endl;
return 0;
} }
system("PAUSE");
return EXIT_SUCCESS;
}