读取数字时出现问题
朋友们大家好,我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 ReadLine() 并仅在空白处进行分割,即
You can use
ReadLine()
and just split on whitespace, i.e.,您可以使用 Split 方法将线分成数字。
You can use the Split method, to break the line into numbers.
您的问题是将字符串转换为整数,因为 Console.Readline 始终返回一个字符串。
解析多个整数的方法有很多,但基本上需要使用某种方法来分割字符串。我不知道 C# 中有
Scanner
(但我猜你应该寻找某种标记器来找到它,因为这将是标准名称。编写一个并不难,特别是如果您只希望整数用空格分隔的话,在方法中实现它可能类似于。
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
用这个
Use this
我已经在 HackerRank 上做了很多这样的事情,这里有一个我用来读取整数数组的辅助方法:
这是一个示例,读取一行上的两个数字,然后将包含这些数字的两行读取到数组中:
示例输入:
I've been doing this on HackerRank a lot, here's a helper method I use for reading an array of integers:
Here's a sample reading two numbers on one line, then two lines with those many numbers into arrays:
Sample input: