2013-08-03 36 views
1

如果「toParse」中只有一個字符且字符爲「+」或「0」,我想返回「大獎」。什麼是最優雅的方式來做到這一點?我試過這個,但顯然它不起作用,因爲它無時無刻都會返回「大獎」。const char *與角色測試相等

char* ParseNRZI::parse(const char* toParse){ 
    if (toParse=="+"||toParse=="0") 
     return "jackpot"; 
} 
+1

你沒有第二個'return'聲明... – nneonneo

回答

3

使用strcmp如果你比較C風格的指針爲char

char* ParseNRZI::parse(const char* toParse) 
{ 
    if (strcmp(toParse, "+") == 0 || 
     strcmp(toParse, "0") == 0) 
    { 
     return "jackpot"; 
    } 
    return "something else"; 
} 

或者,如果你使用std::string你可以使用operator==自由

std::string ParseNRZI::parse(const std::string& toParse) 
{ 
    if (toParse == "+" || 
     toParse == "0") 
    { 
     return std::string("jackpot"); 
    } 
    return std::string("something else"); 
} 

對於設計的角度來看,你是擰檢查功能不是真正的解析功能。然後,你可以重寫你的函數:

bool isJackpot(const std::string& value) 
{ 
    if (toParse == "+" || 
     toParse == "0") 
    { 
     return true; 
    } 
    return false; 
} 

,它可以簡化爲:

bool isJackpot(const std::string& value) 
{ 
    return value.find_first_of("0+") != std::string::npos; 
} 

注:在所有分支它會調用未定義的行爲你的函數並不總是返回char*toParse+0。當函數返回類型不是void時,確保所有函數分支都返回一個值。

+0

因此,在其他情況下,返回「中頭彩」(當它不是+ 0也)是一個未定義的行爲的原因? – Slazer

+0

我的意思是如果它不返回... – billz

+0

好吧,我現在明白了。 – Slazer

0
const char* ParseNRZI::parse(const char* toParse) const 
    { 
     if ((toParse != 0) && 
      (toParse[0] == '+' || toParse[0] == '0') && 
      (toParse[1] == 0) 
     ) 
     return "jackpot"; 

     return ""; 

    } 
+0

如果我不能將返回類型更改爲const char *,該怎麼辦?我知道它只發出警告,但我的程序不能產生任何警告。 – Slazer

+0

@Slazer - 如果你從返回'char *'的函數中返回一個字符串字面值,那麼你會拋出const正確性。遲早你會將該指針傳遞給修改其目標字符串的函數,並且你的代碼會神祕地炸燬。不要通過在他們周圍竊取來修復警告。理解他們的意思和他們爲什麼在那裏,如果警告告訴你一些有用的東西(就像它在這裏),然後聽取建議,不要做你想做的事情。 「我不允許更改返回類型」不是編寫破損代碼的有效理由。 –