чтение двух целых чисел в одной строке с помощью C #

Из https://gist.github.com/geekontheway/2667442 : просто нажмите клавишу «r» или «R», чтобы обновить текущее дерево. Может быть сопоставлен с автоматическим обновлением в .vimrc.

29
задан Nadeem 7 October 2010 в 12:56
поделиться

5 ответов

Один из вариантов - принять одну строку ввода как строку и затем обработать ее. Например:

//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();

//Parse element 0
int a = int.Parse(tokens[0]);

//Parse element 1
int b = int.Parse(tokens[1]);

Одна из проблем этого подхода заключается в том, что он потерпит неудачу (выбрасывая IndexOutOfRangeException / FormatException), если пользователь не введет текст в ожидаемом формате. Если это возможно, вам придется проверить ввод.

Например, с регулярными выражениями:

string line = Console.ReadLine();

// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(@"^\d+\s+\d+$").IsMatch(line))
{
   ...   // Valid: process input
}
else
{
   ...   // Invalid input
}

В качестве альтернативы:

  1. Убедитесь, что вход разбивается на ровно 2 строки.
  2. Используйте int.TryParse - , попытайтесь разобрать строки в числа.
27
ответ дан 28 November 2019 в 01:40
поделиться

Затем вы должны сначала сохранить его в строку, а затем разбить его, используя пробел в качестве токена.

5
ответ дан 28 November 2019 в 01:40
поделиться
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
2
ответ дан 28 November 2019 в 01:40
поделиться
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SortInSubSet
{
    class Program
    {

        static int N, K;
        static Dictionary<int, int> dicElements = new Dictionary<int, int>();
        static void Main(string[] args)
        {

            while (!ReadNK())
            {
                Console.WriteLine("***************** PLEASE RETRY*********************");
            }

            var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;

            foreach (int ele in sortedDict)
            {
                Console.Write(ele.ToString() + "  ");
            }

            Console.ReadKey();
        }

        static bool ReadNK()
        {
            dicElements = new Dictionary<int, int>();
            Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");

            string[] NK = Console.ReadLine().Split();

            if (NK.Length != 2)
            {
                Console.WriteLine("Please enter N and K values correctly.");
                return false;
            }

            if (int.TryParse(NK[0], out N))
            {
                if (N < 2 || N > 9999)
                {
                    Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
                    return false;
                }
            }
            else
            {
                Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
                return false;
            }

            if (int.TryParse(NK[1], out K))
            {
                Console.WriteLine("Enter all elements Separated by space.");
                string[] kElements = Console.ReadLine().Split();

                for (int i = 0; i < kElements.Length; i++)
                {
                    int ele;

                    if (int.TryParse(kElements[i], out ele))
                    {
                        if (ele < -99999 || ele > 99999)
                        {
                            Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
                            return false;
                        }

                        dicElements.Add(i, ele);
                    }
                    else
                    {
                        Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
                        return false;
                    }

                }

            }
            else
            {
                Console.WriteLine(" Invalid number ,Value of 'K'.");
                return false;
            }


            return true;
        }
    }
}
0
ответ дан 28 November 2019 в 01:40
поделиться
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
1
ответ дан 28 November 2019 в 01:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: