使用 C# 在一行中读取两个整数

发布于 2024-09-26 08:08:01 字数 208 浏览 4 评论 0原文

我知道如何让控制台读取两个整数,但每个整数本身就像这样,

int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());

如果我输入两个数字,即(1 2),值(1 2),无法解析为整数 我想要的是,如果我输入 1 2 那么它会将其视为两个整数

i know how to make a console read two integers but each integer by it self like this

int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());

if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

山有枢 2024-10-03 08:08:02

一种选择是接受单行输入作为字符串,然后对其进行处理。
例如:

//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尝试将字符串解析为数字。

One option would be to accept a single line of input as a string and then process it.
For example:

//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]);

One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.

For example, with regular expressions:

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
}

Alternatively:

  1. Verify that the input splits into exactly 2 strings.
  2. Use int.TryParse to attempt to parse the strings into numbers.
那小子欠揍 2024-10-03 08:08:02

您需要类似(没有错误检查代码)的内容,

var ints = Console
            .ReadLine()
            .Split()
            .Select(int.Parse);

它读取一行,在空格上拆分并将拆分的字符串解析为整数。当然,实际上您需要检查输入的字符串是否实际上是有效的整数(int.TryParse)。

You need something like (no error-checking code)

var ints = Console
            .ReadLine()
            .Split()
            .Select(int.Parse);

This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).

楠木可依 2024-10-03 08:08:02

那么你应该首先将它存储在一个字符串中,然后使用空格作为标记来分割它。

Then you should first store it in a string and then split it using the space as token.

梦年海沫深 2024-10-03 08:08:02

将行读入字符串,拆分字符串,然后解析元素。一个简单的版本(需要添加错误检查)是:

string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);

Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:

string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
若水微香 2024-10-03 08:08:02
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
带刺的爱情 2024-10-03 08:08:02

得益于 LinQ 和正则表达式,在 1 行中(无需类型检查)

var numbers = from Match number in new Regex(@"\d+").Matches(Console.ReadLine())
                    select int.Parse(number.Value);

in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)

var numbers = from Match number in new Regex(@"\d+").Matches(Console.ReadLine())
                    select int.Parse(number.Value);
死开点丶别碍眼 2024-10-03 08:08:02
string x;
int m;
int n;

Console.WriteLine("Enter two no's seperated by space: ");

x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);

Console.WriteLine("" + m + " " + n);

这应该可以根据您的需要工作!

string x;
int m;
int n;

Console.WriteLine("Enter two no's seperated by space: ");

x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);

Console.WriteLine("" + m + " " + n);

This Should work as per your need!

我的奇迹 2024-10-03 08:08:02
public static class ConsoleInput
{
    public static IEnumerable<int> ReadInts()
    {
        return SplitInput(Console.ReadLine()).Select(int.Parse);
    }

    private static IEnumerable<string> SplitInput(string input)
    {
        return Regex.Split(input, @"\s+")
                    .Where(x => !string.IsNullOrWhiteSpace(x));
    }
}
public static class ConsoleInput
{
    public static IEnumerable<int> ReadInts()
    {
        return SplitInput(Console.ReadLine()).Select(int.Parse);
    }

    private static IEnumerable<string> SplitInput(string input)
    {
        return Regex.Split(input, @"\s+")
                    .Where(x => !string.IsNullOrWhiteSpace(x));
    }
}
终弃我 2024-10-03 08:08:02
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
千里故人稀 2024-10-03 08:08:02

试试这个:

string numbers= Console.ReadLine();

string[] myNumbers = numbers.Split(' ');

int[] myInts = new int[myNumbers.Length];

for (int i = 0; i<myInts.Length; i++)
{
    string myString=myNumbers[i].Trim();
    myInts[i] = int.Parse(myString);
}

希望有帮助:)

Try this:

string numbers= Console.ReadLine();

string[] myNumbers = numbers.Split(' ');

int[] myInts = new int[myNumbers.Length];

for (int i = 0; i<myInts.Length; i++)
{
    string myString=myNumbers[i].Trim();
    myInts[i] = int.Parse(myString);
}

Hope it helps:)

你另情深 2024-10-03 08:08:02
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;
        }
    }
}
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;
        }
    }
}
星星的轨迹 2024-10-03 08:08:02

我有一个更简单的解决方案,使用 switch 语句并在每种情况下使用以 ("\n") 开头的 Console.write() 为用户编写一条消息。

下面是在获取用户输入时使用 for 循环填充数组的示例。 * 注意:您不需要编写 for 循环即可使其工作*
使用名为 arrayOfNumbers[] 的整数数组和临时整数变量尝试此示例。在单独的控制台应用程序中运行此代码,并观看如何在同一行上获取用户输入!

           int temp=0;
           int[] arrayOfNumbers = new int[5];

        for (int i = 0; i < arrayOfNumbers.Length; i++)
            {
      switch (i + 1)
                {
                    case 1:
                        Console.Write("\nEnter First number: ");
                        //notice the "\n" at the start of the string        
                        break;
                    case 2:
                        Console.Write("\nEnter Second number: ");
                        break;
                    case 3:
                        Console.Write("\nEnter Third number: ");
                        break;
                    case 4:
                        Console.Write("\nEnter Fourth number: ");
                        break;
                    case 5:
                        Console.Write("\nEnter Fifth number: ");
                        break;


                    } // end of switch

                    temp = Int32.Parse(Console.ReadLine()); // convert 
                    arrayOfNumbers[i] = temp; // filling the array
                    }// end of for loop 

这里的魔术是你欺骗了控制台应用程序,秘密是你在编写提示消息的同一行上获取用户输入。 (message=>“输入第一个数字:”)

这使得用户输入看起来像是被插入到同一行中。我承认它有点原始,但它可以满足您的需要,而不必为如此简单的任务浪费时间在复杂的代码上。

I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").

Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!

           int temp=0;
           int[] arrayOfNumbers = new int[5];

        for (int i = 0; i < arrayOfNumbers.Length; i++)
            {
      switch (i + 1)
                {
                    case 1:
                        Console.Write("\nEnter First number: ");
                        //notice the "\n" at the start of the string        
                        break;
                    case 2:
                        Console.Write("\nEnter Second number: ");
                        break;
                    case 3:
                        Console.Write("\nEnter Third number: ");
                        break;
                    case 4:
                        Console.Write("\nEnter Fourth number: ");
                        break;
                    case 5:
                        Console.Write("\nEnter Fifth number: ");
                        break;


                    } // end of switch

                    temp = Int32.Parse(Console.ReadLine()); // convert 
                    arrayOfNumbers[i] = temp; // filling the array
                    }// end of for loop 

The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")

This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文