Hello is there a different way to convert a int back to a char see comment about half way down the code. Im thinking the use of a switch or an if statement but i cannot figure out hot to apply it. i used char RPS[] = {'?', 'R', 'P', 'S'};
#include <iostream>
using namespace std;
#include <ctime>
#include <cstdlib>
//human choice function
int hchoice()
{
char entry;
int usrchoice = 0;
while (1)
{
cout <<"Choose R for Rock P for Paper, S for Sissors or Q for quit ";
cin >> entry;
cin.ignore(1000, 10);
switch (toupper(entry)){
case 'R':
usrchoice = 1;
break;
case 'P':
usrchoice = 2;
break;
case 'S':
usrchoice = 3;
break;
case 'Q':
usrchoice = -1;
break;
}
if (usrchoice != 0)break;
cout << "Invalid Entry" <<endl;
}
return usrchoice;
}
//Computer choice function
int compchoice()
{
return (1 + rand() % 3);
}
void printresults(int computer, int human)
{
//Number to char converter? Can i use a switch here?
char RPS[] = {'?', 'R', 'P', 'S'};
cout << "Computer:" << RPS[computer];
cout << ", Human:" << RPS[human];
cout << ", ";
if (computer == human){
cout <<"tie";
}
else if ( ( human==1 && computer == 2) || (human == 2 && computer == 3) || (human == 3 && computer == 1)){
cout << "computer wins!";
}
else {
cout <<"Human Wins!";
}
cout << endl;
}
int main()
{
// initialize the computer's random number generator
srand(time(0)); rand();
// declare variables
int human = 0, computer = 0;
// start loop
while (1)
{
// determine computer's choice
computer = compchoice();
// prompt for, and read, the human's choice
human = hchoice();
// if human wants to quit, break out of loop
if (human == -1) break;
// print results
printresults(computer, human);
cout << endl;
// end loop
}//while
// end program
return 0;
}
You could use a switch there, or a series of if statements. However, what you have right now is by far the most concise and -- I would argue -- the easiest to read.
One more general thing that I would suggest is to use symbolic constants (e.g. an enum) instead of the hard-coded numbers 1, 2 and 3 that you have in several places in your code.
Related
I'm making a game that tests the ASCII strength of a user versus a bot. (There is also a 2 player mode but that's working fine.) The full description is given at the top of my .cpp file. As a basic breakdown, the bot opens a txt file with 500 common four letter words and inserts them into a size 500 array. It then randomly generates a number to pick a random one, and then goes through the process of tovalue() to recieve its ASCII value, where in tovalue() runs through chartoint() four times, one for each character of the word. My issue is that the program calculates the ASCII value perfectly fine of the user generated word, but always returns 0 (0000) for the botword, no matter what the word.
I've tried a few iterations of the generateword() function including using a vector but always get the same resutls. I've done a lot of digging about this and haven't quite found any solutions, although I suspect that the chartoint() function could be better optimized, just not sure how to impliment any better solutions for this specific case. Also, don't think the problem is with chartoint() since it works fine for user input, but I'm pretty sure the problem is with generateword(). Suggestions for making chartoint() would be helpful, but its not my main priority right now since I just need the program to 100% work first. Also, I've confirmed that all of the words in my .txt file are all caps and only four characters per line.
// Write the code for a game called “ASCII Strength” of a four-letter word selected by Player 1
// followed by a four-letter word selected by Player 2. The result would be the sum
//of the ASCII value of each of the letters of the selected words and whoever has higher sum (called ASCII strength) wins.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;;
int chartoint(char a) {
switch (a) {
case 'A':
return 1;
break;
case 'B':
return 2;
break;
case 'C':
return 3;
break;
case 'D':
return 4;
break;
case 'E':
return 5;
break;
case 'F':
return 6;
break;
case 'G':
return 7;
break;
case 'H':
return 8;
break;
case 'I':
return 9;
break;
case 'J':
return 10;
break;
case 'K':
return 11;
break;
case 'L':
return 12;
break;
case 'M':
return 13;
break;
case 'N':
return 14;
break;
case 'O':
return 15;
break;
case 'P':
return 16;
break;
case 'Q':
return 17;
break;
case 'R':
return 18;
break;
case 'S':
return 19;
break;
case 'T':
return 20;
break;
case 'U':
return 21;
break;
case 'V':
return 22;
break;
case 'W':
return 23;
break;
case 'X':
return 24;
break;
case 'Y':
return 25;
break;
case 'Z':
return 26;
break;
}
return 0;
}
int tovalue(string input) {
int first = chartoint(input[0]);
int second = chartoint(input[1]);
int third = chartoint(input[2]);
int fourth = chartoint(input[3]);
cout << first << second << third << fourth; // EXISTS TO TEST CALCULATION
int value = first + second + third + fourth;
return value;
}
string generateword() {
string arr[500];
ifstream file("words.txt");
if (file.is_open())
{
for (int i = 0; i < 500; i++) {
string temp;
getline(file, temp);
arr[i] = temp;
}
file.close();
}
else
{
cout << "Error: Unable to open file.";
exit(0);
}
srand(time(0));
int random_index = rand() % 500;
string random_word = arr[random_index];
return random_word;
}
int main()
{
cout << "Welcome to ASCII strength, a game where the strongest word wins!";
cout << "\nTo play, you must enter a four letter word. The program will calculate the 'ASCII strength' of your word and compare it to your opponent.";
cout << "\nWhoever has the higher sum will win!";
char another;
another = 'y';
while (another == 'y' || another == 'Y') {
cout << "\nWould you like to play against a friend, or against a bot? (F/B)";
char mode;
cin >> mode;
if (mode == 'F' || mode == 'f') {
cout << "\nPlayer 1, please input your four letter word in all caps: ";
string answer1;
cin >> answer1;
int value1;
value1 = tovalue(answer1);
cout << "\nPlayer 2, please input your four letter word in all caps: ";
string answer2;
cin >> answer2;
int value2;
value2 = tovalue(answer2);
if (value1 > value2) {
cout << "\nPlayer 1 wins!";
}
else if (value2 > value1) {
cout << "\nPlayer 2 wins!";
}
else if (value1 == value2) {
cout << "\nTie!";
}
}
else if (mode == 'B' || mode == 'b') {
cout << "\nPlease input your four letter word in all caps: ";
string answer;
cin >> answer;
int valueanswer;
valueanswer = tovalue(answer);
string botword;
botword = generateword();
cout << "\nThe bot generates a random word based on a list of popular four letter words.";
cout << "\nThe bot has generated this word: " << botword;
int valuebot;
valuebot = tovalue("botword");
cout << valueanswer << " " << valuebot; // THIS EXISTS PURELY TO TEST WHETHER THE VALUES ARE PROPERLY CALCULATING
if (valueanswer > valuebot) {
cout << "\nYou win!";
}
else if (valuebot > valueanswer) {
cout << "\nThe bot wins!";
}
else if (valueanswer == valuebot) {
cout << "\nTie!";
}
}
cout << "\nWould you like to start a new game? (y/n)";
cin >> another;
}
}
Your problem is this line:
valuebot = tovalue("botword");
Since all characters in "botword" are lowercase, you get all 0 score. You probably meant to write
valuebot = tovalue(botword);
This is what I've tried so far including my entire project code for the small class project game. Honestly struggle with arrays and don't even know where to start. The project requirements were to Display a menu (use a switch statement to implement the menu) of actions. Then to display the user has chosen to attack or not attack. Then pick up an item randomly and add the random item to one of 6 items in an array named knapSack. Then display the user picked up the item and its random name along with an option to display the Knap Sacks contents (sorted). I'm actually dropping out of computer science, but if I don't pass this assignment I fail so man I'm begging LMAO.
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
int
main ()
{
//Variables
const double stepForest = 50;
const double stepDungeon = 100;
const double stepHouse = 4000;
const double stepMaze = 6000;
//Direction of walking
string North;
string South;
string East;
string West;
//Direction
string direction;
double step;
double steps;
//Asking how many steps
string sSteps;
int nSteps = 0;
//Not allowing negative steps
while (cout << "How many steps are you taking? " << endl
&& !(cin >> nSteps) || nSteps < 0)
{
cin.clear ();
cout << "ERROR: Illegal input!" << endl;
}
//Asking direction user is moving in
cout << "Which direction? (North, West, South, or East) " << endl;
cin >> direction;
//Steps for forest
if (steps >= stepForest && direction == "North");
{
cout << "You have reached the forest. " << endl;
}
//Steps for dungeon
if (steps >= stepDungeon && direction == "South")
{
cout << "You have reached the dungeon. " << endl;
}
//Steps for house
else if (steps >= stepHouse && direction == "East")
{
cout << "You have reached the house. " << endl;
}
//Steps for maze
else if (steps >= stepMaze && direction == "West")
{
cout << "You have reached the maze. " << endl;
}
{
//For menu
int input ();
void output (float);
//Drop down meny bar selections
float result;
int choice, num;
cout << ("Press 1 to attack\n");
cout << ("Press 2 to not attack\n");
cout << ("Press 3 to pick up an item\n");
cout << ("Press 4 to display Knapsack contents\n");
cout << ("Enter your choice:\n");
choice = input ();
//Attack option
switch (choice)
{
case 1:
{
cout << ("You have chosen to attack\n");
cout << ("Your character has attacked\n");
output (result);
break;
}
//No attack option
case 2:
{
cout << ("You have chosen not to attack\n");
cout << ("You do nothing\n");
output (result);
break;
}
//Picking up item option
case 3:
{
cout << ("You have picked up an item\n");
cout << ("The item has been added to Knapsack\n");
//Random array output for knapSack items
char sorteio1[50][11] =
{ "Sword", "Scarf", "Spear", "Knife", "Katana", "Bow" };
int i;
i = rand () % 50;
cout << ("%s\n", sorteio1[i]);
cout << ("The item you picked up was\n"); //This is where I wanted to insert the random
array
cout << (int ());
// Maybe: "knapsack[count] = loot" *****
// loot= randomItems[randomNumber] *****
//Knapsack contents
output (result);
break;
}
case 4:
{
printf ("1.Sword \n");
printf ("2.Scarf \n");
printf ("3.Spear \n");
printf ("4.Knife \n");
printf ("5.Katana \n");
printf ("6.Bow \n");
output (result);
break;
}
printf ("wrong Input\n");
}
}
int number;
scanf ("%d", &number);
return (number);
{
//To quit game
int choice, num;
bool quit = false;
cout << "Would you like to quit (y/n)? ";
cin >> choice;
//If player chooses to quit
if (choice == 'y')
{
cout << "Goodbye you have chosen to quit the game. See you next time! ";
}
else
{
quit = true;
//If player chooses not to quit, but its the end fo the program anyways so
if (choice == 'n')
{
cout <<
"You have chosen not to quit the game. But this is the end anyways! ";
}
quit = false;
return 0;
}
}
I am new to c++. I have given assignment in which i have to calculate grades and ask input from the user. If he enter wrong input i have to start program again. If the user enters correct input i have to process data and again ask if he wants to check for another calculation.I have written this code so far. I don't know how to loop back again in the program if the user enters wrong input and to start program again if it is successful. Please Give me guidance over it. Thanks.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
//Promptin User to Enter his/her Choice
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
if (input != 'c' || input != 'C'){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 's' || input != 'S' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 't' || input != 'T' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input == 'a' || input == 'A'){
}
system("pause");
return 0;
}
You can do it using a simple do while loop:
bool valid_input = false;
do
{
// Code to read and validate the input...
} while (valid_input == false);
If the input is valid, then you set valid_input to true and the loop will end.
On an unrelated note, if you don't case about upper- or lower-case, use e.g. std::tolower so you only have to compare the letter once. E.g. std::tolower(input)
!= 'c'.
Here is the code that will prompt the user for answer as long as the answer is defined withing switch statement. ans is a variable to hold a character either 1 or 0 corresponds to the user's input (defined in switch cases or not). If defined, then ans gets 1 other wise it gets value 0. Do While loop repeats while ans is 1 (defined within switch statement).
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char input;
char ans; //correct answer, incorrect answer
do {
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
switch (input){
case 'S':
ans = 1;
break;
case 's':
ans = 1;
break;
case 'C':
ans = 1;
break;
case 'c':
ans = 1;
break;
case 'T':
ans = 1;
break;
case 't':
ans = 1;
break;
default:
ans = 0;
}
} while (ans);
return 0;
}
User input handling is very common and can normally use similar patterns.
Basically, you re-ask for the input. You handle the valid choices and break out of the loop and you show an error when the choice is invalid and let the loop ask the input again.
Remark1: by not using switch-case here, I can break out of the loop immediately. I break immediately to avoid specifying the conditions twice or using flags, that is also why I use a loop without end-condition.
Remark2: std::flush is used to input on the prompt line. It makes sure that the prompt is shown before waiting for input.
char inp = 0;
while (true) {
std::cout << "Give input (a, b): " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (inp == 'a') {
std::cout << 'a\n';
break;
}
if (inp == 'b') {
std::cout << 'b\n';
break;
}
std::cout << "invalid choice (" << inp << ")";
}
The invalid choice handling can be done a bit more generic by this function, but the handling of the valid choices must still be done locally:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
char askInputChoice(const std::string& prompt, const std::vector<char>& valid)
{
char inp = 0;
while (true) {
std::cout << prompt << ": " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (std::find(valid.begin(), valid.end(), inp) != valid.end()) {
break;
}
std::cout << "invalid choice (" << inp << ")\n";
}
return inp;
}
int main()
{
char inp = askInputChoice("Give input (a, b)", std::vector<char>{'a','b'});
switch (inp) {
case 'a':
std::cout << "a\n";
break;
case 'b':
std::cout << "b\n";
break;
}
}
To restart the program, put it in a while loop, add a choice to quit ('q') and break when that choice is given.
Thanks Guys for All Your Support. Actually it is my First Program in C++ and sorry i have used the word guidance. Actually i have compiled it successfully. Kindly Check my program i know u do not need to but i want to know if i can add more into it to improve it.
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
int addTest = 0, matricMarks = 0 , interMarks = 0 , result = 0;
start: //Label
system("cls"); // Clear the Screen
//Prompting User to Enter his/her Choice
cout<<"Please Select the Degree Programme in which you are interested in to take Addmission: ";
cout<<"\nEnter C or c for Computer Science: "<<endl ;
cout<<"Enter S or s for Software Engineering: "<<endl;
cout<<"Enter T or t for Telecom Engineering: \n"<<endl;
cout<<"\nSelect any option from the above Menu: ";
cin>>input;
//Switch Statement Started
switch(input){
//Case C Started
case 'c':
case 'C':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 70)
{
cout<<"\nCongratulations! You are eligible for the Computer Science degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not qualify for Computer Science Degree Programme: "<<endl;
system("pause");
}
break;
}//Case C Closeed
//Case s Started
case 's':
case 'S':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 85)
{
cout<<"\nCongratulations! You are eligible for the Software Enginnering degree program :)"<<endl;
}
else
{
cout<<"\nSorry! you Do not Qualify for Software Engineering Degree: "<<endl;
system("pause");
}
break;
}//Case S Closed
//Case t Started
case 't':
case 'T':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 80)
{
cout<<"\nCongratulations! You are eligible for the Telecom Engineering degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not Qualify for Telecom Enginnering Degree Programme: "<<endl;
system("pause");
}
break;
}//Case t Closed
//Default Case Started
default:
{
cout<<"\nInvalid input! Enter the correct option again: \n";
system("pause");
goto start; //Jump To Label Start
}//Deafult Case Closed
}// Switch Statement Close
//do while Loop Started
do{
cout<<"\nDo you want to check your eligibility in some other degree program y/n? : ";
cin>>choice;
if (choice=='Y'||choice=='y')
{
goto start; //jump to Label start:
}
else if (choice=='N'||choice=='n')
{
break;
}
}while(choice == 'y' || choice == 'Y');
//Do while Loop Closed
system("pause");
return 0;
}
I am new to C++ and programming in general and was trying to figure out a way to create a switch in C++ to trigger when a number entered is divisible by 3, by 5, and by both 3 and 5. Here is what I have so far:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number;
cout << "Please input a number and then press the enter key" << endl;
cin >> number;
switch (number){
case "/3":
cout << "Fizz" << endl;
break;
case "/5":
cout << "Buzz" << endl;
break;
case "/3" "/5":
cout << "FizzBuzz" << endl;
break;
default:
cout << "Please select another number." << endl;
}
}
Any help with this would be greatly appreciated! :)
In C++ the switch labels must be compile-time evaluable constant expressions that are integral types.
"/3", for example, is a string literal and so does not fit that requirement.
In this case, use number % 3 == 0 to test for divisibility by 3, and so on and use an if, else block:
if (number % 15 == 0){
/*FizzBuzz - do this one first as my `if` block is not mutually exclusive*/
} else if (number % 3 == 0){
/*Fizz*/
} else if (number % 5 == 0){
/*Buzz*/
}
You can use if else.
int remainder1 = 0, remainder2 = 0;
remainder1 = number % 3;
remainder2 = number % 5;
if(remainder1 == 0 && remainder2 ==0) // both
cout<<"FizzBuzz"<<'\n';
else if(remainder1 == 0) // number can be divided by 3
cout<<"Fizz"<<'\n';
else if(remainder2 == 0) // number can be divided by 5
cout<<"Buzz\n";
else // neither
cout<<"......"<<'\n';
BTW, you do have to read the basic book about C++.
here, you can know more about switch
If you really want to do with switch, here is a method, but is not nice. The easiest way is how Bathsheba said.
#include <iostream>
#include <cmath>
using namespace std;
enum class divided { DivideBy3 , DivideBy5 , DivideBy3and5 }; // "strong enum"
// enum class divided { DivideBy3 , DivideBy5 , DivideBy3and5 }; //also good but can be unsafe
divided getCase(int number)
{
divided div;
if(number%3 == 0)
div = divided::DivideBy3;
if(number%5 == 0)
div = divided::DivideBy5;
if(number%3 ==0 && number%5 == 0)
div = divided::DivideBy3and5;
return div;
}
int main()
{
int numberIn;
cout << "Please input a number and then press the enter key" << endl;
cin >> numberIn;
divided number = getCase(numberIn);
switch (number)
{
case divided::DivideBy3:
cout << "Fizz" << endl;
break;
case divided::DivideBy5:
cout << "Buzz" << endl;
break;
case divided::DivideBy3and5:
cout << "FizzBuzz" << endl;
break;
default:
cout << "Please select another number." << endl;
}
}
look at this for enum vs class enum. Keep going.
I'm having trouble with the hexadecimal part of my c++ program. When I use the switch for hexadecimal nothing returns. also for some reason my binary conversion has a leading 0 I cant seem to get rid of.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
void binary(int, int);
void hex(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
int numb, base;
cout << "Enter a decimel number : ";
cin >> numb;
cout << "Enter a base you want number switched to: ";
cin >> base;
switch (base){
case 2: binary(numb, base); break;
case 8: break;
case 16: hex(numb, base); break;
default: break;
}
}
void binary(int numb, int base)
{
int bin[32] = { 0 };
int i = 0;
do
{
bin[i] = numb%base;
numb = numb / base;
i++;
} while (numb != 0);
cout << "\n";
while (i >= 0){
cout << bin[i];
i--;
}
cout << endl << endl;
}
void hex(int numb, int base){
int i;
int hex[10] = { 0 };
for (i=0; i > 10; i++){
hex[i] = numb%base;
numb = numb / base;
for (i; i > 0; i--)
{
if (hex[i] >= 10)
{
switch (hex[i]){
case 10: cout << "A"; break;
case 11: cout << "B"; break;
case 12: cout << "C"; break;
case 13: cout << "D"; break;
case 14: cout << "E"; break;
case 15: cout << "F"; break;
default: break;
}
}
cout << hex[i];
}
}
cout << endl;
}
binary
The problem is after the first loop, i is one greater than the last index. Just for example, say you enter 1: the do...while loop is entered, the digit 1 is put in array index 0, then i is incremented to 1.
Then, in the second loop, both indexes 1 and 0 are printed. You can solve this by decrementing i before entering this loop:
i--;
while (i >= 0){...}
You should be doing something like that anyway, because if you ended up using all 32 digits, you would try to access bin[32] and the program may crash or output gibberish.
hex
The first loop's condition is infinite:
for (i = 0; i >= 0; i++){...}
It should be the same as your condition in binary:
for (i = 0; numb != 0; i++){...}
But you are not done yet because I've noticed you also have a bug in your printing:
if (hex[i] >= 10)
{
switch (hex[i])
{
case 10:
cout << "A";
break;
...
}
}
cout << hex[i];
If hex[i] is greater than or equal to 10, it gets printed twice, once as a hex letter and once as a decimal number. To solve this you could, for example, use continue instead of break in your switch (to skip the second print), or use else:
if (hex[i] >= 10)
{
switch (hex[i])
{
case 10:
cout << "A";
break;
...
}
}
else
{
cout << hex[i];
}
You also need to make the same correction as in binary:
// decrementing i before entering the loop
// vvv
for (i--; i >= 0; i--){...}
Your revision is not correct, hex should not have a nested loop. It was fine before, just with the corrections I've pointed out.