【问题标题】:C# add line numbers to a text fileC#将行号添加到文本文件
【发布时间】:2011-12-01 08:46:03
【问题描述】:

我正在尝试读取 C# 中的文本文件并将行号添加到行中。

这是我的输入文件:

    This is line one
    this is line two
    this is line three

这应该是输出:

    1 This is line one
    2 this is line two
    3 this is line three

这是我目前的代码:

class Program
{
    public static void Main()
    {
        string path = Directory.GetCurrentDirectory() + @"\MyText.txt";

        StreamReader sr1 = File.OpenText(path);

        string s = "";

        while ((s = sr1.ReadLine()) != null)           
        {
            for (int i = 1; i < 4; i++)
                Console.WriteLine(i + " " + s);
            }

            sr1.Close();
            Console.WriteLine();    
            StreamWriter sw1 = File.AppendText(path);
            for (int i = 1; i < 4; i++)
            {
                sw1.WriteLine(s);
            }

            sw1.Close();               
    }
}

我 90% 确定我需要使用 for cycle 来获取行号,但到目前为止,使用这段代码我在控制台中得到了这个输出:

1 This is line one
2 This is line one
3 This is line one
1 this is line two
2 this is line two
3 this is line two
1 this is line three
2 this is line three
3 this is line three

这是在输出文件中:

This is line number one.
This is line number two.
This is line number three.1 
2 
3 

我不确定为什么在写入文件时不使用字符串变量 s,即使它是之前定义的(另一个块,可能是另一个规则?)。

【问题讨论】:

  • 一般评论:我认为最好有 using(StreamReader){} 和 using(StreamWriter){} 块。而且你应该将你的变量命名为's''line',这更清楚,因为它是一条线:)
  • 我不知道这是问题还是您的代码有问题,但是您的括号不匹配。 while 循环的关闭时间比您从缩进中想象的要早。
  • 你为什么一直从1循环到4?你想每行重复四次吗?
  • @Dan Abramov 不,我认为我需要一个 for 循环来为行编号,但这是我对解决方案的印象,我之前错了
  • +1 用于尝试家庭作业问题并显示代码。这么多作业题都是“给我密码”的形式,根本不费吹灰之力

标签: c# streamreader streamwriter


【解决方案1】:

这是一个主要问题:

        for (int i = 1; i < 4; i++)
            Console.WriteLine(i + " " + s);
        }

您正在使用花括号关闭 for 循环,但没有使用花括号打开它。这意味着上面引用的花括号实际上是在关闭 while 循环,因此您循环执行所有 console.writeline,然后当您写入文件时,您实际上根本没有从文件中读取 - s is "" due范围。

【讨论】:

  • 右花括号属于while循环(缩进错误),for循环没有两个花括号。
  • @Giuseppe R:我认为实际上括号错误的可能性更大,而不是故意在那里结束 while 循环,但我很高兴得到纠正。无论哪种方式,都肯定存在错误,因为 while 循环无法做任何有用的事情,因为很明显,您要将其写入文件的操作必须为读取的每一行完成。
【解决方案2】:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace AppendText
{
    class Program
    {
        public static void Main()
        {
            string path = Directory.GetCurrentDirectory() + @"\MyText.txt";

            StreamReader sr1 = File.OpenText(path);


            string s = "";
            int counter = 1;
            StringBuilder sb = new StringBuilder();

            while ((s = sr1.ReadLine()) != null)
            {
                var lineOutput = counter++ + " " + s;
                Console.WriteLine(lineOutput);

                sb.Append(lineOutput);
            }


            sr1.Close();
            Console.WriteLine();
            StreamWriter sw1 = File.AppendText(path);
            sw1.Write(sb);

            sw1.Close();

        }

    }
}

【讨论】:

  • 在家庭作业问题中,通常不会给出问题的完整解决方案。此外,您的程序正在将新文本连接到旧文本,这显然是不需要的。
  • 我已经设法改变它,现在它使用以下方法创建一个新文件:StreamWriter sw1 = File.CreateText(Mytext2.txt);所以现在它创建了一个新文件。然而。新创建的文件中的输出在一行上。我知道我必须更改 stringbuilder 类中的代码,并且我能够在该行中插入字符: sb.Append("testing " + lineOutput);它们出现在每一行句子的前面,但是当我想为新行插入 \n 时它不起作用。
  • @Chris,抱歉没有意识到这是家庭作业。删除我的帖子可以吗?! :)
  • 没关系,我想通了 -> System.Environment.NewLine :) 感谢您的帮助!
  • @GiuseppeR:不值得删除 IMO,因为它看起来像是一个有效的答案。我和你的代表一起认为你可能没有足够长的时间来接受这个,这就是我标记它的原因。 OP现在已经看到了,所以担心为时已晚。希望他会阅读并理解您的代码,而不仅仅是复制和粘贴它。 :)
【解决方案3】:

注意 FOR 循环,你把它们放在 While 中,所以基本上你是在说:

while ((s = sr1.ReadLine()) != null)

读取的每一行

for (int i = 1; i < 4; i++)

一次写入重复 3 次。

另外,你在 while 内关闭了流,所以在读取第一行之后。

【讨论】:

    【解决方案4】:

    我可以为您提供正确的代码,但因为这是家庭作业,所以我只会问您应该引导您找到正确答案的问题:

    • 为什么在循环中关闭 StreamReader?之后您仍然可以访问它,这可能会导致错误。
    • 为什么你在没有前置索引的情况下在 StreamWriter 中写入?
    • 为什么要在循环中打开 StreamWriter?在循环外打开 StreamWriter 和 StreamReader 不是更好吗?您是否在循环中工作,然后关闭流?

    【讨论】:

      【解决方案5】:
      IEnumerable<string> lines = File.ReadLines(file)
                                      .Select((line,i)=>i + " " + line)
                                      .ToList();
      File.WriteAllLines(file, lines);
      

      【讨论】:

      • 我想你没有明白这是作业,你认为你真的在帮助他吗?
      • @BaptistePernet 理解我的代码就足够了。通过尝试了解其工作原理,他将学到很多东西。
      • @Hasan 绝对。 SO 的重点是通过高质量的答案进行教育,而不仅仅是让某人完成他们的家庭作业。谢谢。
      【解决方案6】:

      打开流

      读取整行并将其存储在临时变量中。 使用计数器来跟踪您阅读了哪一行。 将计数器与 temp 变量连接起来。 将其保存到文件中。 将您的行指针移动到下一行并 重复。

      然后关闭您的流

      【讨论】:

        【解决方案7】:

        您确定要关闭循环内的流while

        【讨论】:

        • 我认为流在while循环之后关闭,因为它在}括号之后
        【解决方案8】:

        您需要将行号添加到每个行字符串。查看String.Format。此外,请尝试在 while 循环之外使用计数器变量来保持行号计数。

        希望这足以让您走上正确的道路,而无需向您提供确切的答案。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-30
          • 2011-01-01
          • 1970-01-01
          • 2012-11-03
          • 2014-11-15
          • 2012-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多