web-dev-qa-db-ja.com

ユーザー入力から整数を読み取る

私が探しているのは、コマンドライン(コンソールプロジェクト)からユーザーによって与えられた整数を読み取る方法です。私は主にC++を知っていて、C#パスから始めました。私はConsole.ReadLine()を知っています。文字列だけを取ります。要するに私はこれの整数版を探しています。

私がしていることを正確に説明してください。

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.

私はこのためにかなり長い間探していました。私はCで多くを見つけたがC#ではない。しかし私は別のサイトで、charからintへの変換を提案するスレッドを見つけました。変換よりも直接的な方法があるはずです。

59
TomG

Convert.ToInt32() 関数を使用して、文字列を整数に変換できます。

int intTemp = Convert.ToInt32(Console.ReadLine());
93
CodingDefined

TryParseを使うことをお勧めします。

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);

こうすれば、 "1q"や "23e"のようなものを解析しようとしても、アプリケーションは例外をスローしません。誰かが誤った入力をしたからです。

Int32.TryParseはブール値を返すので、ifステートメントで使用して、コードを分岐する必要があるかどうかを確認できます。

int number;
if(!Int32.TryParse(input, out number))
{
   //no, not able to parse, repeat, throw exception, use fallback value?
}

あなたの質問へ:ReadLine()はコマンドライン全体を読んでいるので、整数を読むための解決策を見つけることはないでしょう、threforは文字列を返します。できることは、この入力をint16/32/64変数に変換してみることです。

これにはいくつかの方法があります。

変換される入力に疑問がある場合は、文字列、int変数、またはそうでないもののいずれを解析しようとしても、常にTryParseメソッドを使用してください。

更新C#7.0では、out変数は引数として渡される場所で直接宣言できるため、上記のコードは次のようにまとめることができます。

if(Int32.TryParse(input, out int number))
{
   /* Yes input could be parsed and we can now use number in this code block 
      scope */
}
else 
{
   /* No, input could not be parsed to an integer */
}

完全な例は次のようになります。

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var foo = Console.ReadLine();
        if (int.TryParse(foo, out int number1)) {
            Console.WriteLine($"{number1} is a number");
        }
        else
        {
            Console.WriteLine($"{foo} is not a number");
        }
        Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
        Console.ReadLine();
    }
}

ここでは、入力が数値ではなく値0であっても変数number1が初期化されていることがわかります。

50
Marco

入力を型キャストする必要があります。以下を使ってみてください

int input = Convert.ToInt32(Console.ReadLine()); 

値が数値でない場合は例外をスローします。

編集する

私は上記が素早いものであることを理解しています。私は自分の答えを改善したいと思います。

String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
      switch(selectedOption) 
      {
           case 1:
                 //your code here.
                 break;
           case 2:
                //another one.
                break;
           //. and so on, default..
      }

} 
else
{
     //print error indicating non-numeric input is unsupported or something more meaningful.
}
8
Kajal Sinha
int op = 0;
string in = string.Empty;
do
{
    Console.WriteLine("enter choice");
    in = Console.ReadLine();
} while (!int.TryParse(in, out op));
4
font

私はint intTemp = Convert.ToInt32(Console.ReadLine());を使いました、そしてそれはうまくいきました、これが私の例です:

        int balance = 10000;
        int retrieve = 0;
        Console.Write("Hello, write the amount you want to retrieve: ");
        retrieve = Convert.ToInt32(Console.ReadLine());
3
yagohaw

私はあなたの質問に対する良い完全な答えを見なかったので、私はより完全な例を示すつもりです。ユーザーから整数入力を取得する方法を示すいくつかのメソッドが投稿されていますが、これを行うときはいつもあなたもまたする必要があります

  1. 入力を検証する
  2. 無効な入力が与えられた場合、エラーメッセージを表示します。
  3. 有効な入力が与えられるまでループスルーします。

この例は、1以上の整数値をユーザーから取得する方法を示しています。無効な入力が与えられた場合、エラーをキャッチし、エラーメッセージを表示し、正しい入力を再試行するようユーザーに要求します。

static void Main(string[] args)
    {
        int intUserInput = 0;
        bool validUserInput = false;

        while (validUserInput == false)
        {
            try
            { Console.Write("Please enter an integer value greater than or equal to 1: ");
              intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
            }  
            catch (Exception) { } //catch exception for invalid input.

            if (intUserInput >= 1) //check to see that the user entered int >= 1
              { validUserInput = true; }
            else { Console.WriteLine("Invalid input. "); }

        }//end while

        Console.WriteLine("You entered " + intUserInput);
        Console.WriteLine("Press any key to exit ");
        Console.ReadKey();
    }//end main

あなたの質問では、あなたがメニューオプションのためにこれを使いたかったように見えます。したがって、メニューオプションを選択するためにint入力を取得したい場合は、ifステートメントを次のように変更できます。

if ( (intUserInput >= 1) && (intUserInput <= 4) )

ユーザーが1、2、3、または4のオプションを選択する必要がある場合、これは機能します。

2
technoman23

もっと良い方法はTryParseを使うことです:

Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
2
Alexander Bell

この単純な行を使ってください。

int x = int.parse(console.readline());
1
static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number from 1 to 10");
        int counter = Convert.ToInt32(Console.ReadLine());
        //Here is your variable
        Console.WriteLine("The numbers start from");
        do
        {
            counter++;
            Console.Write(counter + ", ");

        } while (counter < 100);

        Console.ReadKey();

    }
0
kunleth