2016-10-16 6 views
-1

私は1から5までの数値しか受け付けることができないこのプログラムを作成しています。switch文を使うだけで、その数値をそれぞれのローマ数字に変えなければなりません。私はint型の問題に苦しんでいます。すでに数字を二重引用符で囲んでみたので、一重引用符は文字のためのものです。私はiostreamをインクルードしてint = numを持っていることを確認しました。intスイッチの場合のトラブル

#include <iostream> //preprocessor directives are included 

using namespace std; 

int main() { 
    int num = 0; 

    cout << "Enter a number from 1 to 5: " << endl; 
    cin >> num; 
    switch (num) { 
    case "1" : 
     cout << "I" << endl; 
     break; 
    case "2" : 
     cout << "II" << endl; 
     break; 
    case "3" : 
     cout << "III" << endl; 
     break; 
    case "4" : 
     cout << "IV" << endl; 
     break; 
    case "5" : 
     cout << "V" << endl; 
     break; 
    } 

} 
+0

あなたのコード周りの数字は私のためにうまくいく...あなたはそれが間違っていることを教えてくれますか?コンパイラの出力? –

+0

この時点では、 "caseラベルが整数定数に還元されない"というエラーのために実行できません。私は私のコンパイラを試してみようと思います。 – Can

+0

それはうまくいった。それがあなたのために働いたことを知らせてくれてありがとう、そうでなければ、私はそれを見つけられなかったでしょう。 – Can

答えて

4

intではなく、文字列の値と比較しています。各caseステートメントから引用符を削除します。

+0

大文字小文字のラベルが整数定数に還元されないというエラーが発生し続けます。私も引用符を削除しました。 – Can

+0

そのコードを投稿してください。 –

+0

#include using namespace std; int main(){ \t \t int num = 0; \t \t cout << "1から5までの数字を入力してください:" << endl; \t \t cin >> num; \t \tスイッチ(NUM){ \t \tケース1: \t \t \t COUT << "I" << ENDL。 \t \t \t break; \t \tケース2: \t \t \tcout << "II" << endl; \t \t \t break; \t \tケース3: \t \t \tcout << "III" << endl; \t \t \t break; \t \tケース4: \t \t \tcout << "IV" << endl; \t \t \t break; \t \tケース5: \t \t \t cout << "V" << endl; \t \t \t break; \t \t \t} – Can

0

入力する変数の種類に関係なく、文字や文字列などを入力することができます。整数として文字列を入力すると、不明な動作や無限ループが発生します。

は申し訳ありません、あなたが1から5

にのみ番号または番号が欲しいCINを指示する方法はありません解決策は以下のとおりです。

使用例外処理:qutesなし

#include <iostream> 

int main() 
{ 
    int num = 0; 
    std::cin.exceptions(); 

    try{ 
      std::cout << "Enter a number from 1 to 5: " << std::endl; 
      std::cin >> num; 
      if(std::cin.fail()) 
       throw "Bad input!"; 
      if(num > 5 || num < 1) 
       throw "only numbers 1 throug 5 are allowed!"; 
    } 
    catch(char* cp) 
    { 
     std::cout << cp << std::endl; 
    } 
    catch(...) 
    { 
     std::cout << "An error occuered sorry for the inconvenience!" << std::endl; 
    } 

    switch (num) 
    { 
     case 1 : 
      std::cout << "I" << std::endl; 
     break; 
     case 2 : 
      std::cout << "II" << std::endl; 
     break; 
     case 3 : 
      std::cout << "III" << std::endl; 
     break; 
     case 4 : 
      std::cout << "IV" << std::endl; 
     break; 
     case 5 : 
      std::cout << "V" << std::endl; 
     break; 
     //default: 
     // std::cout "Bad input! only numbers 1 through 5" << std::endl; 
    } 

    return 0; 
} 
関連する問題