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

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;

Related

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

#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.

(c++)Input needs to be a single character, but it accepts multiple characters and checks the first letter

I'm having a problem with a program I've built.
It should take input from the user and check whether it's 'P' or 'M'.
The problem is that I only want it to work if you enter 'P' or 'M', as it is now it accepts as 'M' anything you type as long as it starts with an 'M' (eg. if you type "morse" it will accept it as 'M').
I'm not a programmer and don't have much knowledge of c++, I just made it for fun. An example of how it is:
int main(){
std::cout << "Enter 'M' or 'P'\n";
char slction;
Inputrror:
std::cin >> slction;
switch (slction) {
case 'M':
goto Morse;
break;
case 'm':
goto Morse;
break;
case 'P':
goto Text;
break;
case 'p':
goto Text;
break;
default:
std::cout << "Please only enter 'M' or 'P'\n;
goto Inputrror;
break;
}
Morse:
std::cout << "Morse\n;"
return 1;
Text:
std::cout << "Text\n;"
return 1;
}
EDIT: I tried to read the input as a string like it was suggested and it now works properly. The correct version:
int main() {
std::cout << "Enter 'M' or 'P'\n";
std::string slction;
Inputrror:
std::cin >> slction;
if (slction == "M" || slction == 'm') {
goto Morse;
}
else if (slction == "P" || slction == 'p') {
goto Text;
}
else {
std::cout << "Please only enter 'P' or 'M'\n";
goto Inputrror;
}
Morse:
std::cout << "Morse\n";
return 1;
Text:
std::cout << "Text\n";
return 1;
}
One comment before I answer:
Instead of
case 'M':
goto Morse;
break;
case 'm':
goto Morse;
break;
you could use
case 'M':
case 'm':
goto Morse;
break;
break stops the block so as long as you don't use it you can nest one after another. You can even do stuff like:
case 'M':
cout << "CAPITALIZED";
case 'm':
goto Morse;
break;
Now, to your question: you are reading a char, meaning it will only take the first letter you input. Use a string instead if you want to be able to read words too:
string slction;
cin >> slction;
PD: remember to change the case 'M' and other options' quotes to double quotes (for strings)
PD2: you can't use switch with strings, so you will have to use if/else blocks
With what was said in the first answer, additionally you could use #include <cctype> toupper() function to remove extra cases. As well as validate your input with if statements.
example validation function:
char isValid(char &selection){
std::cin >> selection;
selection = toupper(selection); // ctype.h for toupper changes all to uppercase characters
//checks to see if more than 1 character is inputed
if (std::cin.get() != '\n'){
std::cin.ignore(256, '\n'); //ignores 256 chars until newline('\n')
std::cin.clear(); // clears the input
selection = '\0'; // sets selection to null
}
return selection;
}
DEMO

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;}

Program skips user input

I was writing a simple calculator in c,whereby the user inputs two numbers and afterward choose the operation to apply on them.(Mul,Add,Div,Sub)The program works except it skips the part where its supposed to take user input for the operand.what am i doing wrong
#include<stdio.h>
#include<sstream>
#include<iostream>
#include<conio.h>
#include<string.h>
using std::cout;
using std::cin;
using namespace std;
int main() {
char Operative[100];
int a;
int b;
int c;
printf("Enter First Number\n");
scanf("%d",&a);
printf("Enter First Number\n");
scanf("%d",&b);
printf("\nPlease Enter Operation(M,A,D,S)");
gets(Operative);
//getline(cin,Operative);
if (Operative == "M")
{
c = a*b;
printf("Multiplication value is %d",c);
}
else if (Operative == "A")
{
c = a+b;
printf("Addition value is %d",c);
}
else if (Operative == "D")
{
c = a/b;
printf("Division value is %d",c);
}
else if (Operative == "S")
{
c = a-b;
printf("\nSubtraction value is %d",c);
}
}
Use strcmp to compare strings values. == compares pointers:
if (strcmp (Operative, "M") == 0) ...
You have to call cin.ignore() (after scanf, before gets) first, because there is still \0 in the buffer.
You can also use switch statement.
switch(operation){
case 'P':
result = a+b;
printf("%d + %d = %d", a,b,result);
.
.
.
Just code this in your int main() if you prefer to use printf and scanf you replace and everything will be ok.
do {
cout << "Option 1 <<endl;
cout << "Option 2 <<endl;
cout << "Option 3 <<endl;
cin >> x;
switch (x) {
case 1:
//Your operation here
break;
case 2:
//Your operation here
break;
case 3:
//Your operation here
break;
case 4:
exit(0);
break;
default:
cout << "Input a valid option" <<endl;
}
} while(x);

How to prevent the user from entering more than one character in the below sample code?

I am facing problem in the below code. If the user enter more than one charater then my loop gets executed number of times equal to the length of the string entered by the user. My code is written in GNU c/c++ compiler.
Thanks in advance.
int continue_option()
{
char c;
loop:
fflush(stdin);
cin.ignore();
cout<<"\n\n\t\t\t\tPress (Y/y) - Continue / Press (N/n) - Exit :";
cin>>c;
if(c=='y'||c=='Y')
{
system("clear");
}
else if(c=='n'|| c=='N')
{
exit(0);
}
else
{
printf("\n\t\t\t\tInvalid Option.Try Again.....");
goto loop;
}
fflush(stdin);
}
First thing, don't use jumps. They are old style, and they make Dijkstra spin in his grave, on top of all the other bad consequences. I don't mean "vintage", I really mean old in the bad sense.
As of your question, I'd rather put the result in a std::string and only consider the first character in there:
std::string input;
std::cin >> input;
switch (input[0]) {
case 'y':
case 'Y':
//your code
break;
case 'n':
case 'N':
exit(0);
default:
std::cout << "Invalid text" << std::endl;
}
I would also refrain from using exit(), I'd rather rely on a function's return value to finally cause a return 0; in the main(), or some equivalent technique.
You can't stop the user from typing more than one character.
What you can do is ignore the rest of the line. You have already use cin.ignore() which ignores one character. You can use cin.ignore(large number) to ignore up to the large number or the end-of-line, whichever appears first.
Unlike flushing output files, fflush(stdin) doesn't really do anything.
Try using cin.get() or getch() to read just one character at a time. Also, I guess you'd be better off replacing the whole thing with a simple loop like:
char ch = '\0';
do
{
ch = getch();
}while((tolower(ch) != 'y') || (tolower(ch) != 'n'))
if(tolower(ch) == 'y')
{
//additional handling
}
else
{
exit(0);
}
Not exactly the same behavior, but should put you on track:
#include <iostream>
#include <iomanip>
bool is_valid_answer(char c)
{
switch(c)
{
case 'y':
case 'Y':
case 'n':
case 'N':
return true;
default:
return false;
}
}
bool continue_option()
{
std::cout << "Press (Y/y) to continue, (N/n) to exit: " << std::flush;
char c = '\0';
while (std::cin.get(c) && !is_valid_answer(c));
return ((c == 'y') || (c == 'Y'));
}
int main()
{
std::cout << "Continue option: " << continue_option() << std::endl;
}