首页 > 解决方案 > 使用 Switch-case 语句拉取随机扑克牌等级和花色以显示用户

问题描述

我要在 main 函数之外设置 Enumeration 并使用 void PlayingCard() 来拉取枚举等级和花色以向用户显示等级和花色。但是我很难编写正确的代码以使其按我希望的方式工作。我对 C++ 相当陌生。任何帮助将不胜感激。

谢谢!

我已经设置了 enum rank() 和 enum suit() 以及它的卡号和套装。然后,我按照教授的指示在 void PrintCard() 函数中设置了 switch-case 语句。我试图将它拉入 main() 函数,但它不会做任何事情。

#include <iostream>
#include <conio.h>

using namespace std;

enum Rank // ace high
{
    TWO = 2, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
};

enum Suit
{
    SPADE, DIAMOND, CLUB, HEART
};

struct Card
{
    Rank rank;
    Suit suit;
};

void PrintCard(Card card);


int main()
{
    int num1 = 2;
    cin >> num1;

        PrintCard;

    _getch();
    return 0;
}
void PrintCard(Card card)
{
    switch (card.rank)
    {
    case 14: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 13: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 12: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 11: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 10: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 9: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 8: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 7: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 6: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 5: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 4: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 3: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    case 2: cout << "The" << card.rank << "of" << card.suit << endl;
        break;
    default: 
        cout << "Wrong Input" << endl;
    }   
}

我希望它在我输入数字时向用户显示西装和等级,但输入只是空白,我无法从 PrintCard 函数中提取任何内容来使用。

标签: c++

解决方案


您没有PrintCard正确调用您的函数:

int main()
{
    int num1 = 2;
    cin >> num1;

    Card card;
    card.rank = Rank::TWO;
    card.suit = Suit::SPADE;
    PrintCard(card);

    _getch();
    return 0;
}

创建一个卡片对象,为其分配等级和花色,然后使用此对象调用您的PrintCard函数。

在你的 cout 中额外添加空格:

cout << "The " << card.rank << " of " << card.suit << endl;

你不需要你的 switch.case 因为每个案例都一样:

void PrintCard(Card card)
{
    cout << "The " << card.rank << " of " << card.suit << endl;
}

如果要打印枚举名称,则必须使用 switch-case。例子:

std::string str;
switch (card.rank):
   case Rank::TWO:
       str = "two";
       break;
       ...

cout << str;

推荐阅读