While in a traditional blackjack game, you don't input your cards, but instead are dealt them, this exercise will still help calculate card values and can be modified into a full game of blackjack. It appears you set it up so that all cards are worth their face value, aside from higher cards such as J, Q, or K. With aces, you are merely counting them.
After you select to play again, it adds to the previous values because they were not re-initialized, so adding re-initialization to the beginning of your do/while loop solves that problem. With your switch statement set up as is, all values should be 2-10, although I don't see any value applied to aces there. The nAces loop only executes if an ace was one of the cards inputted, and applies 1 or 11 based on the total value (it seems logical). I'm unsure about the purpose of the -'0' on line 20, which subtracts from assigned values. There's probably a better way to set this up which would make it easier to debug. Maybe something like this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
using namespace std;
int main()
{
int total=0, nAces=0,value=0;
char c,response;
do
{
cout<<"Enter cards: ";
cin>>c;//takes input and applies to c
c=tolower(c);
if (c=='j' || c=='q' || c=='k')
value=10;
else if (c=='a')
nAces++;
else
value=(char)c;
while (nAces>0)
{
if (total+11<=21)
total+=11;
else
total++;
nAces--;
}
if (total>21)
cout<<"BUSTED!\n";
else if (value==10)
cout<<value<<endl;
else
cout<<(char)value<<endl;
cout<<"Enter more cards? (y/n): ";
cin>>response;
} while (response=='y' || response=='Y');
return 0;
}
|
I can see why you want to use chars in place of strings, but it brings other complications along with it, such as figuring out when to use "(char)" and when to work with the variable alone. That's why this code sample doesn't have the total calculations resolved. Perhaps I need to further educate myself about character/integer conversion to get this to work right, as (char) appears to achieve what is wanted on output, but does not appear to assign values to other variables correctly.