读取数字时出现问题

发布于 2024-11-18 05:23:58 字数 425 浏览 0 评论 0原文

朋友们大家好,我是 C# 的初学者。 我想读取以下格式的数字

2

1 10

3 5

对于读取 2,我使用了 Convert.ToInt32(Console.ReadLine()) 方法并成功存储了它。但对于下一个输入,我想读取该数字,在空格之后我想读取另一个数字。我无法使用 ReadLine() 方法..我使用了 Convert.ToInt32(Console.Read())

但数字 1 被读为 49

那么我如何实现读取数字

在 java 中我找到了一个名为 Scanner 的类似类,其中包含方法行 nextInt() 是否有与该类等效的 C# 类?

简而言之,我只想知道如何在 C# 中读取和存储数字(整数或浮点数)。

Hello friends i am a total beginner in c#.
I want to read numbers in the following format

2

1 10

3 5

For reading 2 i have used Convert.ToInt32(Console.ReadLine()) method and successfully stored it. But for the next input i want to read the number and after a space i want to read another number. I cannot use ReadLine() method.. I have used Convert.ToInt32(Console.Read())

But the number 1 is read as 49

So How do i achieve reading numbers

In java i have found a similar class called Scanner which contains methods line nextInt()
Is there any C# equivalent to that class.

In short i just want to know how to read and store numbers(integers or floats) in C#.

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

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

发布评论

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

评论(5

八巷 2024-11-25 05:23:58

您可以使用 ReadLine() 并仅在空白处进行分割,即

void Main( string[] args )
{
    var numbers = new List<int>();
    while(whatever)
    {
        var input = Console.ReadLine();
        var lines = input.Split( 
            new char[] { ' ' }, 
            StringSplitOptions.RemoveEmptyEntries 
            );

        foreach( var line in lines )
        {
            int result;
            if( !int.TryParse( line, out result ) )
            {
                // error handling
                continue;
            }

            numbers.Add( result );
        }
    }
}

You can use ReadLine() and just split on whitespace, i.e.,

void Main( string[] args )
{
    var numbers = new List<int>();
    while(whatever)
    {
        var input = Console.ReadLine();
        var lines = input.Split( 
            new char[] { ' ' }, 
            StringSplitOptions.RemoveEmptyEntries 
            );

        foreach( var line in lines )
        {
            int result;
            if( !int.TryParse( line, out result ) )
            {
                // error handling
                continue;
            }

            numbers.Add( result );
        }
    }
}
要走干脆点 2024-11-25 05:23:58

您可以使用 Split 方法将线分成数字。

while (true)
{
   var s = Console.ReadLine();
   if (s == null) break;
   foreach (var token in s.Split(' '))
   {
        int myNumber = int.Parse(token);
        // ...  do something ....
   }
}

You can use the Split method, to break the line into numbers.

while (true)
{
   var s = Console.ReadLine();
   if (s == null) break;
   foreach (var token in s.Split(' '))
   {
        int myNumber = int.Parse(token);
        // ...  do something ....
   }
}
只涨不跌 2024-11-25 05:23:58

您的问题是将字符串转换为整数,因为 Console.Readline 始终返回一个字符串。

解析多个整数的方法有很多,但基本上需要使用某种方法来分割字符串。我不知道 C# 中有 Scanner (但我猜你应该寻找某种标记器来找到它,因为这将是标准名称。

编写一个并不难,特别是如果您只希望整数用空格分隔的话,在方法中实现它可能类似于。

   // Optional seperators 
   public IEnumerable<int> ParseInts(string integers, params char[] separators)
   {
       foreach (var intString in integers.Split(separators))
       {
            yield return int.Parse(intString);
       }
   }


   public IEnumerable<int> ParseInts(string integers)
   {
        return ParseInts(integers, ' ');
   }

You problem is about converting strings into integers, as Console.Readline always returns a string.

There are many ways to parse multiple ints, but you will basically need to split the string using some method. I don't know of a Scanner in C# (but I guess you should seach for some kind of tokenizer to find it, since this would be the standard name.

Writing one is not that hard, especially if you only expect integers to be separated by spaces. Implementing it in a method could be something like

   // Optional seperators 
   public IEnumerable<int> ParseInts(string integers, params char[] separators)
   {
       foreach (var intString in integers.Split(separators))
       {
            yield return int.Parse(intString);
       }
   }


   public IEnumerable<int> ParseInts(string integers)
   {
        return ParseInts(integers, ' ');
   }
御守 2024-11-25 05:23:58

用这个

        string[] lines = File.ReadAllLines("Path to your file");
        foreach (string line in lines)
        {
            if (line.Trim() == "")
            {
                continue;
            }
            string[] numbers = line.Trim().Split(' ');
            foreach (var item in numbers)
            {
                int number;
                if (int.TryParse(item, out number))
                {
                    // you have your number here;
                }
            }
        }

Use this

        string[] lines = File.ReadAllLines("Path to your file");
        foreach (string line in lines)
        {
            if (line.Trim() == "")
            {
                continue;
            }
            string[] numbers = line.Trim().Split(' ');
            foreach (var item in numbers)
            {
                int number;
                if (int.TryParse(item, out number))
                {
                    // you have your number here;
                }
            }
        }
伪心 2024-11-25 05:23:58

我已经在 HackerRank 上做了很多这样的事情,这里有一个我用来读取整数数组的辅助方法:

static int [] StringToIntArray(string s) {
    string [] parts = s.Split(' ');
    int [] arr = new int[parts.Length];
    for (int i = 0; i < arr.Length; i++) {
        arr[i] = Convert.ToInt32(parts[i]);
    }
    return arr;
} 

这是一个示例,读取一行上的两个数字,然后将包含这些数字的两行读取到数组中:

string [] parts = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(parts[0]);
int m = Convert.ToInt32(parts[1]);
int [] a = StringToIntArray(Console.ReadLine());
int [] b = StringToIntArray(Console.ReadLine());

示例输入:

3 5
40 50 60
10 20 30 100 7500

I've been doing this on HackerRank a lot, here's a helper method I use for reading an array of integers:

static int [] StringToIntArray(string s) {
    string [] parts = s.Split(' ');
    int [] arr = new int[parts.Length];
    for (int i = 0; i < arr.Length; i++) {
        arr[i] = Convert.ToInt32(parts[i]);
    }
    return arr;
} 

Here's a sample reading two numbers on one line, then two lines with those many numbers into arrays:

string [] parts = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(parts[0]);
int m = Convert.ToInt32(parts[1]);
int [] a = StringToIntArray(Console.ReadLine());
int [] b = StringToIntArray(Console.ReadLine());

Sample input:

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