【问题标题】:continue to print 100 lines at a time if user enters input如果用户输入输入,则继续一次打印 100 行
【发布时间】:2016-11-03 03:22:05
【问题描述】:

我有一个控制台应用程序,它从包含文本行(数千行)的文本文件中打印行。

using (TextReader tr = new StreamReader(__inputfile))
{
    string nextline = tr.ReadLine();
    while (nextline != null)
    {
        Console.WriteLine(nextline);
        nextline = tr.ReadLine();
    }
}

我想改变它,让它只打印 100 行,要求用户在打印接下来的 100 行之前按 Enter 键,依此类推

Console.WriteLine("Press Enter to continue...or Control-C to stop");
Console.ReadLine();

在用户按 Enter 键(或真正的任何键)后,它会打印接下来的 100 行......然后一直这样下去,直到文件用完行,然后程序停止。

【问题讨论】:

  • 您不熟悉设置计数器..?并做一个有条件的if 语句..?这并不难..如果您正在阅读循环外的第一行,那么在您的while循环中读取的行将是1设置一个lineCnt ++然后检查lineCnt = 100,然后让他们做其他事情..现在来吧..

标签: c# file input io


【解决方案1】:

使用模运算符:使用计数器。一开始就将其初始化为0。阅读每一行后增加它。在循环内部有一个检查,如:

if (counter % 100 == 0)
  waitForInput(); 

不带模运算符:用户点击回车后,您还可以将计数器设置为 0 - 在这种情况下,您不需要使用 % 并且只能检查

 if (counter == 100) {
   waitForInput();
   counter = 0;
 }

PS。像这样的:

int counter = 0;
using (TextReader tr = new StreamReader(__inputfile))
{
    string nextline = tr.ReadLine();
    while (nextline != null)
    {
        counter++;
        if(counter == 100)
        {
            Console.WriteLine("Press Enter to continue...");
            Console.ReadLine();
            counter = 0;
        }

        Console.WriteLine(nextline);
        nextline = tr.ReadLine();

    }

}

【讨论】:

    【解决方案2】:

    一种方法可能是简单地跟踪您向控制台写入的行数。当达到 100 行时,停止输出,等待输入,重置计数器或使用 %100,然后恢复循环。

    【讨论】:

      【解决方案3】:
      using (TextReader tr = new StreamReader(__inputfile))
      {
          var count=1;
          string nextline = tr.ReadLine();
      
          while (nextline != null)
          {
              if (count % 100 == 0)
              {
                  Console.WriteLine("Press Enter to continue...or Control-C to stop");
                  nextline=Console.ReadLine();
                  Console.WriteLine(nextline);
              }
              else
              {
                  Console.WriteLine(nextline);
                  nextline = tr.ReadLine();
              }
      
              count++;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-04
        • 2022-11-11
        • 2020-01-20
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        • 2017-06-15
        相关资源
        最近更新 更多