is it possible to covert string expression's result to a int? - c++

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
int main()
{
int a;
string exp1,exp2,sign2,dec2,dec3;
char sign;
float op1=0,op2=0,answer=0,op3=0,exper1=0,exper2=0;
string dec,clear;
/*----------------------------------------------section of choices----------------------------------------------*/
cout<<"Enter the number for desired operation\n"<<endl;
cout<<"Enter '1' for arithmetic operations "<<endl;
cout<<"Enter '2' for increment/decrement operations"<<endl;
cout<<"Enter '3' for logical operations"<<endl;
cin>>a;
/*----------------------------------------------section of Arithmetic operators----------------------------------------------*/
restart:
switch(a)
{
case 1:
cout<<"Section of Arithmetic opearators\n";
cout<<"\n";
cout<<"enter first operand\n";
cin>>op1;
cout<<"Enter operator\n";
cin>>sign;
cout<<"Enter second operand\n";
cin>>op2;
cout<<"if you want to Start calculation press small 's'\ntype 'end' to end programe\n";
cin>>dec;
if(dec=="s")
{
goto start;
}
else
{
goto end;
}
start:
switch (sign)
{
case '+':
answer=op1+op2;
break;
case '-':
answer=op1-op2;
break;
case '*':
answer=op1*op2;
break;
case '/':
answer=op1/op2;
break;
case '=':
answer=op1=op2;
break;
case '>':
answer=op1>op2;
if (answer==0)
{
cout<<"the expression evaluates to fales\n";
}
cout<<"the expression evaluates to true\n";
break;
case '<':
answer=op1<op2;
if (answer==0)
{
cout<<"the expression evaluates to fales\n";
}
cout<<"the expression evaluates to ture\n";
break;
default:
cout<<"Enter a valid arithmetic operator!\n";
}
cout<<"the answer to the operation is "<<answer<<"\n\n\n<<"<<flush;
cout<<"Press 'c' to clear screen and do more operations\n Enter end to end programe\n";
cin>>clear;
if (clear=="c")
{
system("cls");
goto restart;
}
exit(0);
break;
/*----------------------------------------------Increment/Decrement operator----------------------------------------------*/
case 2:
cout<<"Section of increment decrement operatotrs\n";
cout<<"Enter The Operand\n";
cin>>op3;
cout<<"Enter the operator(+ or -)\n";
cin>>sign;
cout<<"if you want to Start calculation press small 's'\ntype 'end' to end programe\n";
cin>>dec2;
if(dec2=="s")
{
goto start2;
}
else
{
goto end2;
}
start2:
switch (sign)
{
case '+':
op3=op3+1;
cout<<"The incremented value is "<<op3<<"\n";
break;
case '-':
op3=op3-1;
cout<<"The decremented value is \n"<<op3<<"\n";
break;
default:
cout<<"enter a valid operator\n\n";
break;
}
cout<<"Press 'C' to clear screen and do more operations\n Enter end to end programe\n";
cin>>clear;
if (clear=="c")
{
system("cls");
goto restart;
}
exit(0);
break;
/*----------------------------------------------Section of logical statements----------------------------------------------*/
case 3:
cout<<"section of logical statements\n";
cout<<"Enter first expression in brackets '()'\n";
cin>>exp1;
istringstream(exp1)>>exper1;
cout<<"Type '&&' or '||' \n";
cin>>sign2;
cout<<"Enter second expression in brackets '()'\n";
cin>>exp2;
istringstream(exp2)>>exper2;
cout<<"if you want to Start calculation press small 's'\ntype 'end' to end programe\n";
cin>>dec3;
if(dec3=="s")
{
goto start3;
}
else
{
goto end3;
}
start3:
if (sign2=="&&")
{
answer=exper1&&exper2;
if (answer==0)
{
cout<<"The experrssion evalutes to false\n";
}
else
{
cout<<"The experession evaluates to ture\n";
}
}
else
{
answer=exper1||exper2;
if (answer==0)
{
cout<<"The experrssion evalutes to false\n";
}
else
{
cout<<"The experession evaluates to ture\n";
}
}
cout<<"Press 'C' to clear screen and do more operations\n Enter end to end programe\n";
cin>>clear;
if (clear=="c")
{
system("cls");
goto restart;
}
exit(0);
break;
default:
cout<<"enter any valid option\n";
}
end:
end2:
end3:
return 0;
}
I am making a simple program which takes two relational expressions from user and use a logical operator to evaluate both of them. I used sstream to convert string into int but i think i am doing it wrong as it only evaluates the int to 0.I just want to get the evaluation of the string and the answer of it whether its 0 or 1 stored into the int data type.

Related

My code works for C++ but not when converted to C language

I am providing the code that I converted to the C language and the converted code as well. The code works just as desired in C++ but I am unable to enter the value of the 'Operator' variable in the C language version.
This is the C++ code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
float num;
float num2;
char Operator;
char choice;
float result;
cout << "Select one of the following items:\n";
cout << "B) - Binary Mathematical Operations, such as addition and subtraction.\n";
cout << "U) - Unary Mathematical Operations, such as square root, and log.\n";
cout << "A) - Advances Mathematical Operations, using variables, arrays.\n";
cout << "V) – Define variables and assign them values.\n";
cout << "E) - Exit\n";
cin >> choice;
if (choice == 'U' || choice == 'u') {
cout << "Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n";
cin >> Operator;
rerun:
cout << "Enter a positive value.\n";
cin >> num;
if (num < 0) {
goto rerun;
}
else {
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
}
cout << fixed << setprecision(2) << result;
}
return 0;
}
This is the C language code:
#include <stdio.h>
#include <math.h>
int main()
{
double num;
char Operator;
char choice;
double result;
printf("Select one of the following items:\n");
printf("B) - Binary Mathematical Operations, such as addition and subtraction.\n");
printf("U) - Unary Mathematical Operations, such as square root, and log.\n");
printf("A) - Advances Mathematical Operations, using variables, arrays.\n");
printf("V) - Define variables and assign them values.\n");
printf("E) - Exit\n");
scanf("%c", &choice);
if (choice == 'U' || choice == 'u') {
printf("Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n");
scanf("%c", &Operator);
printf("Enter a positive value.\n");
scanf("%lf", &num);
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
printf("the answer is %lf", result);
}
return 0;
}
Both the codes are working except I am unable to input the value of the 'Operator' variable in the C version whereas it works great in C++.
Any help regarding this is truly appreciated.
Unlike the equivalent C++ code inputing a character using %c does not skip whitespace. To do that you should add a space before the %c, like this
scanf(" %c",&Operator); // skip whitespace then read a char
This code will work for you!.
Actually you should have better understanding of how buffered input works.
#include <stdio.h>
#include <math.h>
int main()
{
double num;
char Operator;
char choice;
double result;
printf("Select one of the following items:\n");
printf("B) - Binary Mathematical Operations, such as addition and subtraction.\n");
printf("U) - Unary Mathematical Operations, such as square root, and log.\n");
printf("A) - Advances Mathematical Operations, using variables, arrays.\n");
printf("V) - Define variables and assign them values.\n");
printf("E) - Exit\n");
scanf("%c", &choice);
char eat_line;
scanf("%c", &eat_line);
if (choice == 'U' || choice == 'u') {
printf("Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n");
scanf("%c", &Operator);
scanf("%c", &eat_line);
printf("Enter a positive value.\n");
scanf("%lf", &num);
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
printf("the answer is %lf", result);
}
return 0;
}

Personal library, number positive or negative

Implement in C ++, using a personal library, an application that determines based on the choice made by the user if a number is positive or negative or if a number is prime or not.
This is the main code:
#include <iostream>
#include "libreria.cpp"
using namespace std;
int s;
int main()
{
int num1,cont;
cout<<"\n 1) Positive ";
cout<<"\n 2) Prime ";
cout<<"\n 3) Exit ";
cout<<"\n Choose: ";
do
{
cin>>s;
switch (s)
{
case 1:
cout<<"\nInsert the number: ";
cin>>num1;
bool sepos(int numb);
if (bool sepos(int numb)==1)
{
cout<<"\nIl numero "<<num1<<" e' positive";
}
else
{
cout<<"\nIl numero "<<num1<<" e' negative";
}
break;
case 2:
break;
}
} while (s!=3);
return 0;
}
The library is:
bool sepos(int numb)
{
if(numb>=0)
{
return true;
}
else
{
return false;
}
}
For now, I was trying to see if the number was positive or not.
But the application won't work, i got a lot of errors.
[Error] function 'bool sepos(int)' is initialized like a variable
[Error] expected primary-expression before '==' token
[Error] expected '=' before '==' token
[Warning] declaration of 'bool sepos(int)' has 'extern' and is initialized
I've noticed a couple of things you are doing wrong.
The first one is: if (bool sepos(int numb)==1) you are trying to compare a bool value ( true or false ) with the number one. Yes, C++ treats 1 and 0 like true or false but your function already returns true or false.
#include <iostream>
#include "libreria.cpp"
using namespace std;
int s;
int main()
{
int num1,cont;
cout<<"\n 1) Positive ";
cout<<"\n 2) Prime ";
cout<<"\n 3) Exit ";
cout<<"\n Choose: ";
do
{
cin>>s;
switch (s)
{
case 1:
cout<<"\nInsert the number: ";
cin>>num1;
if (sepos(int numb))
{
cout<<"\nIl numero "<<num1<<" e' positive";
}
else
{
cout<<"\nIl numero "<<num1<<" e' negative";
}
break;
case 2:
break;
}
} while (s!=3);
return 0;
}
The other issue is: your function bool sepos(int numb) is declared to return a boolean value, you don't have to cast it.
numb>=0 returns true or false, you don't have to return those values explicitly.
bool sepos(int numb)
{
return numb>=0;
}
My Advice: Try to learn a bit more about the syntax of the language, you can avoid a lot of mistakes.

Using The Result From An If Statement To Execute A Switch Cases?

I'm not sure if this will work. I'm assuming it should , I just can't figure out how.
I am trying to execute a Switch case from the result from an If Statement.
For example if the result from the If is 1 , the first case executes
This is what I'm thinking:
#include <iostream>
#include <ctype.h>
using namespace std;
int main(){
cout<<"\tDetermine what has been inputted"<<endl<<endl;
char value,ch;
int option;
do{
cout<<"Input something: ";
value = islower(value);
cin>>value;
if(value>='0' && value<='0'){
option == 1;
}
else if (value=='a' || value=='e' || value=='i' ||value=='o' ||
value=='u') {
option ==2;
}
switch(option){
case 1:
cout<<"You entered "<<value <<" a digit."<<endl;
cout<<"Do you wish to test again? (Y/N): "<<endl;
cout<<"Do you wish to test again? (Y/N): "<<endl;
cin>>ch;
break;
case 2:
cout<<"You have entered"<<value<<" a vowel"<<endl;
cout<<"Do you wish to test again? (Y/N): "<<endl;
cin>>ch;
break;
default:
cout<<"That input is not valid"<<endl;
}
} while (ch == 'y' || ch =='Y');
return 0;
}
Is what I'm thinking possible?
Intialize variables to avoid UB:
char value,ch = 0;
int option = 0;
this is true only if value is '0':
if(value>='0' && value<='0')
you have two typos: == instead of =
option = 1;
and
option = 2;
You might want to set ch to 'Y' in case of invalid output?
default:
cout<<"That input is not valid"<<endl;

c++ While Loop termination with function

scratching my head on this as it was working just fine earlier but when I went to add some other functions suddenly my program freaked out and I can not get it back to what it was.
class has me writing a rock/paper/scissors program to go up against a computer, any help with why the loop keeps terminating itself would be wonderful
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void RPSout(char);
int RPScomp();
int main() {
char choice;
int endit=0;
while (endit == 0)
{
cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
cin >> choice;
RPSout(choice);
if (choice=='Q'||'q')
{endit=1;}
}
return 0;
}
void RPSout(char choose)
{
int RPS =0;
int comp=0;
switch (choose)
{
case 'R':
case 'r':
{
cout <<"Your choice: Rock";
break;
}
case 'P':
case 'p':
{
cout <<"Your choice: Paper";
break;
}
case 'S':
case 's':
{
cout << "Your choice: Scissors";
break;
}
case 'Q':
case 'q':
{
cout << "Bye Bye Bye";
break;
}
default:
cout<<"You enter nothing!"<<endl;
cout << "The valid choices are R/P/S/Q)";
}
return;
}
int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
unsigned seed = time(0);
srand(seed);
comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
return comp;
}
if (choice=='Q'||'q')
This is equivalent to
if ((choice == 'Q') || 'q')
Which is almost certainly not what you want. 'q' is a non-zero char literal, which is "truthy" and so this expression will never be false. It's akin to writing if (choice == 'Q' || true).
The solution is:
if (choice=='Q' || choice=='q')
The statement
if (choice=='Q'||'q')
always tests true and therefore sets your flag to terminate the loop.
Try:
if (choice=='Q'||choice=='q')
I think your if statement should be if (choice=='Q'|| choice=='q')
Your issue if with the if statement
if (choice=='Q'||'q')
{endit=1;}
the || 'q' part will always be true since 'q' in ASCII is not 0
Change your code to
if (choice=='Q'|| choice=='q')
{endit=1;}

Switch statement behavior in C++

I'm having trouble understanding my C++ switch statement.
I have to enter the accepted integer interval twice for the function to return to the switch. And then it falls straight through to case 2.
Inherited Class:
class Fugl : public DyrLuft
{
private:
int alder;
public:
Fugl() : DyrLuft()
{ }
void les()
{
do
{
cout << "\nSkriv inn fuglens alder: ";
cin >> alder;
if(alder < 0 || alder > 130)
cout << "\nDenne alderen virket usannsynlig, prøv igjen!\n";
} while(alder < 0 || alder > 130);
}
};
Main:
int main()
{
char valg = '\q';
cout << "Hvilken dyreart ønsker du å registrere? (Q for å avslutte)"
<< "\n1) - Fugl \n2) - Fisk \n3) - Insekt \n4) - Skalldyr\n";
do
{
cin >> valg;
switch(valg)
{
case '1':
{
Fugl fugl; fugl.les();
} break;
case '2':
{
Fisk fisk; fisk.les();
} break;
case '3':
{
Insekt insekt; insekt.les();
} break;
case '4':
{
Skalldyr skalldyr; skalldyr.les();
} break;
case 'Q': return 0;
case 'q': return 0;
default: cout << "Velg en av ovennevnte!\n";
}
} while(valg != 'Q' || valg != 'q');
return 0;
}
I dont know what is happening in your case, but I ran your code and it works just fine for me. Entered 1,4,Q and program exited as expected....Could be a compiler or a DyrLuft class issue(i just removed the inheritance to make it work, also lines from case 2,3,4).
You have:
case '1':
{
Fugl fugl; fugl.les();
} break;
When you run this you create a Fug1 object and then you call the les() function. When you enter an appropriate age in les() the function returns. Since the break; is outside of the case block it is actually breaking the switch statement and going to the end of the loop. Then it cycles back to the top of the loop and makes you enter a selection again. If you move break inside og the case block it functions as it should. This is the changed loop:
do
{
cout << "Hvilken dyreart ønsker du å registrere? (Q for å avslutte)"
<< "\n1) - Fugl \n2) - Fisk \n3) - Insekt \n4) - Skalldyr\n";
cin >> valg;
switch (valg)
{
case '1':
{
Fugl fugl; fugl.les();
break;
}
case '2':
{
Fisk fisk; fisk.les();
break;
}
case '3':
{
Insekt insekt; insekt.les();
break;
}
case '4':
{
Skalldyr skalldyr; skalldyr.les();
break;
}
case 'Q': return 0;
case 'q': return 0;
default: cout << "Velg en av ovennevnte!\n";
}
} while (valg != 'Q' || valg != 'q');