StreamReader中的无限循环
本文关键字:无限循环 StreamReader | 更新日期: 2023-09-27 18:27:10
我有一个应用程序,它应该向用户询问商品编号,搜索文本文件,然后显示带有该商品编号的商品。然而,我的程序经历了一个无限循环。我在这里做错了什么?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise
{
class Inventory
{
static void Main()
{
FileStream file = new FileStream(@"SoldItems.txt",
FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file);
int count = 0;
int num;
string item;
item = reader.ReadLine();
while (item != null)
{
++count;
item = reader.ReadLine();
}
int size = (int)file.Length / count;
Console.Write("Item Number? ");
num = Convert.ToInt32(Console.ReadLine());
while (num != 0)
{
file.Seek(0, SeekOrigin.Begin);
item = reader.ReadLine();
Console.WriteLine(item);
}
reader.Close();
file.Close();
}
}
}
输出看起来像:
101-灯,100.00美元
102-Rug,5000.00美元
问题出现在以下代码中:
Console.Write("Item Number? ");
num = Convert.ToInt32(Console.ReadLine());
while (num != 0)
{
file.Seek(0, SeekOrigin.Begin);
item = reader.ReadLine();
Console.WriteLine(item);
}
num永远不会改变,从而导致无限循环。您应该在循环的每次重复中读取值:
Console.Write("Item Number? ");
num = Convert.ToInt32(Console.ReadLine());
while (num != 0)
{
file.Seek(0, SeekOrigin.Begin);
item = reader.ReadLine();
Console.WriteLine(item);
Console.Write("Item Number? ");
num = Convert.ToInt32(Console.ReadLine());
}
你想做一些类似的事情:
Console.Write("Item Number? ");
num = Convert.ToInt32(Console.ReadLine());
while (num != 0)
{
// Do your seek operations here
// run this again so you won't be stuck in the loop
num = Convert.ToInt32(Console.ReadLine());
} {
file.Seek(0, SeekOrigin.Begin);
item = reader.ReadLine();
Console.WriteLine(item);
}