2017-08-24 219 views
0

我正在使用switch語句和C++,我通過一些示例並使用了一個獨立的示例來完成。我選擇的例子是從eur到gbp的貨幣轉換器。在所有情況下,我的代碼都會恢復爲默認值,就像輸入了錯誤的單位一樣。發生這種情況,直到我將輸入從'€符號或'£'符號更改爲'E'或'P'。我想知道我哪裏錯了。我的代碼示例如下。C++ Switch語句和符號

// Currency: Convert GBP to EUR or Vice Versa 

int main(){ 

    double gbp_to_eur = 1.09; 
    double eur_to_gbp = 0.92; 
    char unit = '£'; 
    double amount_to_convert = 0; 
    int AnyKey = 0; 

    cout << "Please enter the the unit you'd like to convert \n"; 

    cin >> unit; 

    cout << "\n \n Now please enter the amount you'd like to convert. \n"; 

    cin >> amount_to_convert; 

    switch (unit) { 
    case 'P': 
     cout << "Your " << unit << amount_to_convert << " is worth €" << amount_to_convert * gbp_to_eur << '.\n'; 
     break; 
    case 'E': 
     cout << "Your " << unit << amount_to_convert << " is worth €" << amount_to_convert * eur_to_gbp << '.\n'; 
     break; 

    default: cout << "The compiler isn't programmed for this unit of currency. \n"; 
     break; 
    } 


    cin >> AnyKey; 
} 
+3

€和£在你的語言環境,這可能是UTF-8可能多字節字符。因此,你不能用一個'char'來表示它們。 –

+1

您應該在調試器中打開一塊手錶,並查看內存中的實際外觀。你可能會感到驚訝。 –

+1

請編輯您的問題包含[mcve] – Slava

回答

0

£是Unicode符號,並且因此不適合於一個8位char。您的編譯器希望爲該行提供warning: multi-character character constant的警告。

你應該能夠與解決此問題:

#include <cwchar> 

... 

wchar_t x = u'£'; 
+1

8位字符,而不是字節:) –

+0

@MichaelDorgan哈哈,謝謝。 – 0x5453