gpt4 book ai didi

c# - Peek() 永远不会评估为负数

转载 作者:行者123 更新时间:2023-11-30 20:52:50 25 4
gpt4 key购买 nike

我正在学习 C 和 C#,这个问题是针对 C# 的。我有这个 while 循环,它导致无限循环。我以前用过这个,它总是很好用。但现在它只是永远循环,永远不会退出。我正在执行此 while 循环以计算文件中的行数。

代码如下:

                using (TextReader obj2 = new StreamReader(combined))
{
int count = 1;
while (obj2.Peek() != -1)
{
count++;
}
obj2.Close();
TextWriter obj = File.AppendText(combined);
Console.Write("How many lines do you want to add to the file?:");
int numberOfLines = 0;
int lineNumer = count + 1;
numberOfLines = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < numberOfLines; i++)
{
Console.Write("Enter a line of text:");
string line = Console.ReadLine();
obj.WriteLine(lineNumer + ". " + line);
}
}

最佳答案

Peek()不推进读者。您需要在循环内调用 obj2.Read(),否则它永远不会像您看到的那样终止。

来自链接的 MSDN 引用:

Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the reader.

另见 Read()在 MSDN 上。

这两种方法经常协同工作,因此您可以在不影响它的情况下检查流是否已结束。您走在正确的轨道上!

关于c# - Peek() 永远不会评估为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20543887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com