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;}
Related
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;
}
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;
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);
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;
}
This program is supposed to teach functions. I have separated the functions each into header files. I think there is a curly brace somewhere that is backwards or missing, but I have stared at this program for hours and tried re-arranging things and can't seem to get anything going.
This program is supposed to read a phone number and print it out. If it is provided letters then it will sort it to a number 0-9 like on a phone keypad, after making it an uppercase letter. It will also return error codes for invalid characters, etc., which is controlled by a switch statement.
Main function
One of the errors I am getting is on the closing brace on the last line:
expected '}' at end of input
#include <iostream>
#include <cctype>
#include "Read_Dials.h"
#include "To_Digit.h"
#include "Acknowledge_Call.h"
using namespace std;
int main()
{
char digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8;
int return_value = 0;
return_value = int Read_dials(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8);
if (return_value != -5)
break;
switch(return_value){
case -1:
cout << "ERROR - An invalid character was entered. Please try again, only numbers or letters this time." << endl;
break;
case -2:
cout << "ERROR - Phone number cant start with 0." << endl;
break;
case -3:
cout << "ERROR - This isn't the movies, Phone numbers dont start with \" 555 \" here buddy :/" << endl;
break;
case -4:
cout << "ERROR - Please make sure the hyphen is in position 4." << endl;
break;
default:
void Acknowledge_Call(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8);
}
return 0;
}
Read_Dials Function
No errors in this function
int Read_Dials(char &num1, char &num2, char &num3, char &num4, char &num5, char &num6, char &num7, char &num8)
{
#include "To_Digit.h"
int i = 0;
do{
i++;
cout << "Please enter the character for position #" << i << " in the phone number\n";
cout << "NOTE: Please put the hyphen \" - \" in the fourth position and use \"Q\"to quit." << endl;
char temp;
cin >>temp;
if (i = 1 && temp == 0)
{
return_value = -2;
}
else if (i == 1 && (temp == 'q' || temp == 'Q'))
{
return_value -5;
}
else if (i == 1)
{
temp = &num1;
&inputValue = &num1;
int To_Digit(char &num1);
}
else if (i == 2)
{
temp = &num2;
&inputValue = &num2;
int To_Digit(char &num2);
}
else if (i == 3)
{
temp = &num3;
&inputValue = &num3;
int To_Digit(char &num3);
}
else if (&num1 == '5' && &num2 == '5' && &num3 == '5')
{
return_value -3;
}
else if (i == 4 && temp != '-')
{
return_value -4;
}
else if (i == 5)
{
temp = &num5;
&inputValue = &num5;
int To_Digit(char &num5);
}
else if (i == 6)
{
temp = &num6;
&inputValue = &num6;
int To_Digit(char &num6);
}
else if (i == 7)
{
temp = &num7;
&inputValue = &num7;
int To_Digit(char &num7);
}
else if (i == 8)
{
temp = &num8;
&inputValue = &num8;
int To_Digit(char &num8);
}
}while (i < 8)
return 0;
}
To_Digit Function
The second and final error I'm getting is here, on the second line (the opening brace):
A function-definition is not allowed here before '{' token
int To_Digit(char &inputValue)
{
char &inputValue;
if (isdigit(&inputValue))
break;
&inputValue = toupper(&inputValue);
switch(&inputValue){
case 'A': case 'B': case 'C':
&inputValue = '2';
break;
case 'D': case 'E': case 'F':
&inputValue = '3';
break;
case 'G': case 'H': case 'I':
&inputValue = '4';
break;
case 'J': case 'K': case 'L':
&inputValue = '5';
break;
case 'M': case 'N': case 'O':
&inputValue = '6';
break;
case 'P': case 'Q': case 'R': case 'S':
&inputValue = '7';
break;
case 'T': case 'U': case 'V':
&inputValue = '8';
break;
case 'W': case 'X': case 'Y': case 'Z':
&inputValue = '9';
break;
default:
return -1;
}
}
Acknowledge_Call function
No errors with this function.
void Acknowledge_Call(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8)
{
cout << "Phone number entered is: " << digit1 << digit2 << digit3 << digit4 << digit5 << digit6 << digit7 << digit8 << endl;
}
What's wrong with this code? How can I fix it?
I haven't tried to run the code myself just yet, but the only thing I can see that looks hokey to me is in the "Read_Dials" function... don't put a #INCLUDE statement within a function. Always place those statements at the top of the file.
Move the #include and let us know what that does.
Good luck.
default:
void Acknowledge_Call(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8);
Return type is not used while calling a function. So, drop void. Also default case should have a break, else it will fall-through.
int Read_Dials(char &num1, char &num2, char &num3, char &num4, char &num5, char &num6, char &num7, char &num8)
{
#include "To_Digit.h" // The header actually has a definition. Preprocessor
// copies the content of To_Digit.h here. So, you have
// a function definition inside another function while
// compilation phase which is not allowed. So remove
// it and place it at top of the file.
// .....
}
Your #includes should be at the top of the file...
if (return_value != -5)
break;
(in main) is not allowed as there is no loop for it to break out of
Here are some issues (besides the fact you didn't supply header files):
Function declaration after "default" in main()
Remove the void in front of the function call.
Types for parameters not specified in declaration for Acknowledge_Call
Change to:
void Acknowledge_Call(char digit1, char digit2, char digit3, char digit4, char digit5, char digit6, char digit7, char digit8)
Remove the int in front of Read_dials in the main function.
In main(), change 'Read_dialstoRead_Dials:
The C++ language is case-sensitive, thus 'dials != Dials != dIaLs.
Remove break from after if in main() function:
You want return 1; or return EXIT_FAILURE; or exit(1);
Remember to add these lines to Acknowledge_Calls.cpp:
#include "acknowledge_call.h"
#include <iostream>
using namespace std;
Remember to add these lines to Read_Dials.cpp:
#include "read_dials.h"
#include <iostream>
using namespace std;
In Read_Dials.cpp, move the #include "To_Digit.h to the top of the file.
When executing a function all, do not put the return type nor the parameter types in the call.
For example, use:
num1 = To_Digit(digit1);
instead of
int To_Digit(char &num1);
You need to have a long talk with your instructor about how to call functions and pass parameters (this time, listen carefully). Also, read a good book on C++.