1

我正在尝试学习 C#,因为我在那里没有什么经验。我想在循环中设置一个 Console.Readline,Do While这样我就可以将未知数量的值读入一个数组。它永远不会退出,因此中的比较while不起作用。怎么了?

do
{
    line = Console.Read();
    if (line != null)
        numbers[c++] = line;
    numbers = new int[c+1];

} while (line != null);
4

2 回答 2

2

如果您正在使用,Console.Readline()那么如果linenull按下Ctrl+Z(如@Patrick 所述)。您应该检查空字符串:

    do
    {
        line = Console.ReadLine();
        if (line != null)
            numbers[c++] = int.Parse(line); //assigning string to the last element in the array of ints?
            //if you need to parse string to int, use int.Parse() or Convert.ToInt32() 
            //whatever suits your needs
        numbers = new int[c+1];

    } while (!string.IsNullOrEmpty(line));

无论如何,当您在每次迭代中创建新数组时,尚不清楚您要使用此代码完成什么。此外,这将不起作用,因为您有一个数组int但为其分配了一个string值。

于 2014-12-10T20:32:33.143 回答
2

首先,我会使用 aList<int>来保存输入值。这避免了重新排列数组的必要性,您可以将列表用作普通数组。

其次,Console.Read 和 Console.ReadLine 有很大的不同。第一个逐一返回键入的字符的字符代码,按下Enter将仅返回Enter键的字符代码(13)。要退出循环,您需要按Ctrl+Z返回 -1,而不是 null。

List<int> numbers = new List<int>();
int line;
do
{
    line = Console.Read();
    if (line != -1)
        numbers.Add(line);
} while (line != -1);
for(int x = 0; x < numbers.Count(); x++)
   Console.WriteLine(numbers[x]);

但是,这可能不是您真正想要的。如果您需要将键入的数字存储为实整数,则需要如下代码:

List<int> numbers = new List<int>();
string line = Console.ReadLine();
int number;
do
{
    if(int.TryParse(line, out number))
        numbers.Add(number);

} while (!string.IsNullOrWhiteSpace(line = Console.ReadLine()));
for(int x = 0; x < numbers.Count(); x++)
   Console.WriteLine(numbers[x]);

在这个版本中,我在进入循环之前获得线路输入,然后继续直到Enter按下键。在每个循环中,我都尝试将输入转换为有效的整数。

还要注意使用 TryParse 将字符串转换为整数。如果您的用户键入“abcdef”之类的内容,TryParse 将返回 false 而不会引发异常。

(感谢@Patrick的建议。)

于 2014-12-10T20:52:16.413 回答