在if语句不正常的情况下进行Char比较

时间:2016-01-30 12:44:39

标签: c++ if-statement char statements

我有几个if语句将一个类的私有字符与一个字符进行比较(例如' c'或' d')但是它没有分配我运行它时的正确价值,我不知道问题是什么。这是代码:

ostream & operator<<(ostream &out, const Card &rhs)
{
   string string_suit;
   string string_rank;

   /*switch(rhs.suit)
   {
       case 'c': string_suit="Clubs"; 

       case 'd': string_suit="Diamonds"; 
              break;
       case 'h': string_suit="Hearts"; 
              break;
       case 's': string_suit="Spades"; 
              break;
       default : string_suit= "error"; 
   }*/

   if(rhs.suit == 'c')
   {
      string_suit="Clubs";
   }

   else if(rhs.suit == 'd')
   {
      string_suit ="Diamonds";
   }

   else
   {
      string_suit = "error";
   }


   if(rhs.rank==1)
      string_rank="Ace";

   else if(rhs.rank==11)
      string_rank="Jack";

   else if(rhs.rank==12)
      string_rank="Queen";

   else if(rhs.rank==13)
      string_rank="King";
   else
   {

      ostringstream convert;
      convert << rhs.rank;
      string_rank=convert.str(); //rhs.rank;
   }   

   out<<string_rank<<" of "<<string_suit ;
   return out; 
}

1 个答案:

答案 0 :(得分:1)

您错过了切换声明中的break;:所以&#39; d&#39;案件总是被执行,即使rhs.suit是&#39; c&#39;。但是,if语句总能正常工作。

ostream & operator<<(ostream &out, const Card &rhs){
    string string_suit;
    string string_rank;
    switch(rhs.suit)
    {
        case 'c': string_suit="Clubs"; 
                  break;
        case 'd': string_suit="Diamonds"; 
                  break;
        case 'h': string_suit="Hearts"; 
                  break;
        case 's': string_suit="Spades"; 
                  break;
        default : string_suit= "error"; 
    }

    if(rhs.rank==1)
      string_rank="Ace";
    else if(rhs.rank==11)
      string_rank="Jack";
    else if(rhs.rank==12)
      string_rank="Queen";
    else if(rhs.rank==13)
      string_rank="King";
    else {
      ostringstream convert;
      convert << rhs.rank;
      string_rank=convert.str(); //rhs.rank;
    }   
    out<<string_rank<<" of "<<string_suit ;
    return out;
}