StreamReader中的无限循环

时间:2014-10-20 22:40:00

标签: c# visual-studio-2013

我有一个应用程序,它应该向用户询问项目编号,搜索文本文件,然后显示带有该项目编号的项目。但是,我的程序经历了无限循环。我在这里做错了什么?

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 - 地毯,$ 5,000.00

2 个答案:

答案 0 :(得分:0)

问题在于此代码:

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());
}

答案 1 :(得分:0)

你想做类似的事情:

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);
    }