Decimal to binary/hex using arrays - c++

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.

Related

ASCII Strength Game will not calculate "Bot" word value

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

C++ pull a card from deck

I'm trying to create a program that will pull a card from a deck of 52 regular playing cards.
Suits: Heart, Spad, Diamond, Club.
Rank: A,2,3,4,5,6,7,8,9,10,J,Q,K.
This should be the output:
Let's pull a card!
This time we got AH
Wanna pull a card again?
y
This time we got 3J
Wanna pull a card again?
n
My output is:
Let's pull a card!
DKThis time we got 00
Wanna pull a card again?
n
This is my code:
#include <iostream>
#include <ctime>
using namespace std;
// Function Declaration
int rankCard(), suitCard();
int main()
{
srand(time(0));
char answer;
cout << "Let's pull a card!" << endl;
do {
cout << "This time we got " << rankCard() << suitCard() << endl;
cout << "Wanna pull a card again?" << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
int rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: cout << "A";
break;
case 10: cout << "T";
break;
case 11: cout << "J";
break;
case 12: cout << "Q";
break;
case 13: cout << "K";
break;
default: cout << rank;
break;
}
return 0;
}
int suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: cout << "H";
break;
case 2: cout << "D";
break;
case 3: cout << "C";
break;
case 4: cout << "S";
break;
}
return 0;
}
I can't figure out why the cards pulled (DK) are in that position and why I also get the 00. What am I doing wrong? Thanks
Your calls to rankCard() and suitCard() always return 0.
That 0 value is what's passed to cout in your main function.
The weird 'DK' is caused by the calls to cout inside rankCard and suitCard.
You could modify your functions to avoid the confusion:
#include <string>
std::string rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: return "A";
case 10: return "T";
case 11: return "J";
case 12: return "Q";
case 13: return "K";
default: return std::to_string( rank );
}
return "";
}
std::string suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: return "H";
case 2: return "D";
case 3: return "C";
case 4: return "S";
}
return "";
}
This line:
cout << "This time we got " << rankCard() << suitCard() << endl;
So those functions print the card, and then they return 0, so if you call them in cout, they will do their thing witch is printing the card and then print the return value witch is 0.
What you can do is to call them outside the cout, just do:
//...
cout << "This time we got ";
rankCard();
suitCard();
cout << endl;
cout << "Wanna pull a card again?" << endl;
//...
Personally I would refactor the functions to return the respective card char:
Live sample
const char rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: return 'A';
case 10: return 'T';
case 11: return 'J';
case 12: return 'Q';
case 13: return 'K';
default: return rank + 48; // convert to decimal digit
}
}
const char suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: return 'H';
case 2: return 'D';
case 3: return 'C';
case 4: return 'S';
default: return 0; //ASCII code for null character
}
}

Guessing Game with functions c++

I am writing a guessing game program using functions for each thing, I keep getting errors saying function isn't set so when I try to call it, it isn't working. I can't figure out what I am doing wrong.
I know I have arguments for the functions that aren't being used but I cant seem to figure out where or how I should include those in the function themself.
I am fairly new to programming/c++ so please no negative comments I am just trying to get as much help as I can.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int getGuess(string prompt);
string getRank(int guessCount);
bool getPlayAgain(string prompt);
void playOneGame();
int main(){
srand(time(0));
int number = rand() % 100 + 1;
string prompt = getGuess();
do(
playOneGame();
)while(getPlayAgain())
return EXIT_SUCCESS;
}
int getGuess(string prompt){
int num;
int guessCount = 0;
prompt = cout << "Please enter a number between 1-100: ";
cin >> num;
if(num > 100){
cout << "Please enter a number between 1-100: " << endl;
}
if(num < 1){
cout << "Please enter a number between 1-100: " << endl;
}
if(num <= 100){
cout << "The number you guessed is: " << num << endl;
guessCount++;
}
}
string getRank(int guessCount){
switch(guessCount){
case 1:
case 2:
case 3: cout << "Lucky!" << endl;
break;
case 4:
case 5:
case 6: cout << "Awesome";
break;
case 7:
case 8:
case 9: cout << "Good";
break;
case 10:
case 11:
case 12: cout << "Meh";
break;
case 13:
case 14:
case 15: cout <<"Poor";
break;
default: cout << "Pathetic";
}
}
bool getPlayAgain(string prompt){
bool done = false;
int num1;
while(!done){
cout << "Enter 1 to play again or 2 to quit: ";
cin >> num1;
if(num1 == 2){
break;
}
else(
getGuess();
)
}
}
void playOneGame(){
getGuess();
getRank();
getPlayAgain();
}
No return statement in getguess() function but function signature is int return type.
Getguess() accepts prompt parameter as input but not used inside the function.

If statements in for loops

how do I run only one of those if statements in a for loop? For example i have an input of 5...and i just want it to print five...but whenever i run this code, it will execute all if statement..please help me
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int a;
int b;
cin >> a;
for (a = 0; 0<a<10; a++)
{
if (a == 1)
{
cout << "one";
}
if (a == 2)
{
cout << "two";
}
if (a == 3)
{
cout << "three";
}
if (a == 4)
{
cout << "four";
}
if (a == 5)
{
cout << "five";
}
if (a == 6)
{
cout << "six";
}
if (a == 7)
{
cout << "seven";
}
if (a == 8)
{
cout << "eight";
}
if (a == 9)
{
cout << "nine";
}
else if (a > 9 && a%2 == 0)
{
cout << "even";
}
else if (a > 9 && a&2 != 0)
{
cout << "odd";
}
}
return 0;
}
The problem seems to be the for loop. Your program accepts a value for a as an input, but then as soon as the loop begins, it resets the value of a to 0 (for (a = 0;...
Therefore it's looping 10 times, and on each loop a will have a different value, starting from 0 and ending at 9. This means that all of your if statements will get hit at some point in the execution, generally one on each of the loops round the for.
To get your expected behaviour " input of 5...and i just want it to print five", simply remove the for loop from your code.
Your unnecessary for loop trashes the input value of a and loops forever! (At least until you overflow your signed type a).
You are replacing a by using it as the counter in the for loop! If you only ever want one output, then drop the for loop completely. If your for loop were to remain then your expression 0 < a < 10 ought to be recast as 0 < a && a < 10 : formally 0 < a < 10 is evaluated as (0 < a) < 10 which is either true < 10 or false < 10 which is always true.
Also consider refactoring your if else to set up explicitly mutually exclusive statements:
if (a == 1){
cout << "one";
} else if (a == 2){
cout << "two";
/*and so on*/
} else {
/*all other cases*/
}
Although in this case you might want to consider a switch block:
switch (a){
case 1:
cout << "one";
break; // to stop program control flowing into the next case
case 2:
cout << "two";
break;
/*and so on*/
default:
/*all other cases*/
}
if () {
} else if () {
}
Although,
switch() {
}
will be more efficient in your case.
Update 1
#Aleph0
Below is the solution
int main() {
int a;
cin >> a;
switch (a) {
case 1: cout << "one"; break;
case 2: cout << "two"; break;
case 3: cout << "three"; break;
case 4: cout << "four"; break;
case 5: cout << "five"; break;
case 6: cout << "six"; break;
case 7: cout << "seven"; break;
case 8: cout << "eight"; break;
case 9: cout << "nine"; break;
default: cout << ((a & (1 << 31)) ? "negative" : (a & 1) ? "odd" : "even"); break;
}
}
Question has been asked to do following
i have an input of 5...and i just want it to print five
And, someone has correctly mentioned above, for loop is immaterial here.

converting Roman numerals into decimal

Hey guys I think I'm really close with but I'm not too sure how to continue. All of the questions related to my problem don't really answer anything. The error that I'm getting right now is an
(33): error C2064: term does not evaluate to a function taking 1 arguments
(41): error C2064: term does not evaluate to a function taking 1 arguments
Header file:
using namespace std;
class romanType
{
public:
void printRoman(char romanNum);
int printDecimal(int& total);
int convertRoman(int& total);
void setRoman(char& roman);
romanType();
romanType(char);
private:
char romanNum[6];
int decimal;
int total;
};
Implementation:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include "romanType.h"
using namespace std;
romanType::romanType(char)
{
};
void romanType::printRoman(char romanNum)
{
cout << "Here is your number in Roman Numeral form: " << romanNum << endl;
};
int romanType::printDecimal(int& total)
{
cout << "Here is your number in Decimal form: " << total << endl;
return total;
};
void romanType::setRoman(char& romanNum)
{
};
int romanType::convertRoman(int& total)
{
int len = 0;
len = strlen(romanNum);
int count[1];
for(int i = 0; i < len; i++)
{
switch(romanNum[i])
{
case 'M':
count[i] = 1000;
break;
case 'm':
count[i] = 1000;
break;
case 'D':
count[i] = 500;
break;
case 'd':
count[i] = 500;
break;
case 'C':
count[i] = 100;
break;
case 'c':
count[i] = 100;
break;
case 'L':
count[i] = 50;
break;
case 'l':
count[i] = 50;
break;
case 'X':
count[i] = 10;
break;
case 'x':
count[i] = 10;
break;
case 'V':
count[i] = 5;
break;
case 'v':
count[i] = 5;
break;
case 'I':
count[i] = 1;
break;
case 'i':
count[i] = 1;
break;
default:
cout << "Error.." << endl;
}
total = total + count[0];
}
return total;
};
My main:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include "romanType.h"
using namespace std;
int main()
{
romanType r;
char romanNum;
char choice;
int decimal;
int total;
cout << "Hello! Please enter your Roman Numeral: " << endl;
cin >> romanNum;
cout << endl;
r.setRoman(romanNum);
r.convertRoman(total);
cout << "Do you want the Roman Numeral or the Decimal?" << endl;
cout << "Press [D] for Decimal!" << endl << "Press [R] for Roman Numeral!" << endl;
cin >> choice;
if (choice == 'D' || choice == 'd')
r.printDecimal(total);
else if (choice == 'R' || choice == 'r')
r.printRoman(romanNum);
else
cout << "That wasn't the right button!" << endl;
system ("pause");
return 0;
}
I'm pretty sure I'm on the right track. It would be nice to see any tips or advice relating to my errors.
Thanks in advance
From just a quick look at the code, I might suggest looking through the debug window at the values of your variables at each step. What I am seeing is two variables, one char type named romanNum, and an entirely different one that is a char array named romanNum. It gets a little confusing but could work if you are only asking the user for a single char in roman numerals which then you wouldn't need an array at all. Otherwise, you could get a string then convert that into an array.
Start there and see if that helps.