-4

我正在尝试从文本文件构建表格,但是:当我编译程序时,输入的信息出现在它应该出现的表格之后,但表格是空白的。显然我在某个地方犯了一个错误..你能帮忙吗?

   StreamReader swreNames = File.OpenText("Names.txt");

        do
        {
            Console.SetCursorPosition(15, 2);
            Console.Write("--- Names Table ---");
            Console.SetCursorPosition(10, 4);
            Console.Write("First Name");
            swrNames.WriteLine(firstname); // Reads from first name from file Names.txt
            Console.SetCursorPosition(10, Counter + 6); // Aligns first name within table settings 
            Console.SetCursorPosition(28, 4);
            Console.Write("Surname");
            swrNames.WriteLine(lastname); // Reads from last name from file Names.txt
            Console.SetCursorPosition(28, Counter + 6);
            Console.SetCursorPosition(48, 4);
            Console.Write("Age");
            swrNames.WriteLine(age); // Reads from age from file Names.txt
            Console.SetCursorPosition(48, Counter + 6);
            Console.ReadLine();
            Console.Clear();
        } while ((firstname = swreNames.ReadLine()) != null); //Writes out the input from the text file

好的,我已经编辑了代码以显示我认为有问题的地方,希望它的阅读格式稍微容易一些!

请帮忙。

4

2 回答 2

2

Ok, let's suppose that your file's content follow the format [first name] [last name], like:

Axl Rose
Joey Ramone
Steve Vai
BB King

So, your code would look like:

        StreamReader fileContent = File.OpenText(@"C:\my-file.txt");

        Console.SetCursorPosition(15, 2);
        Console.Write("--- Names Table ---");
        Console.SetCursorPosition(10, 4);
        Console.Write("First Name");
        Console.SetCursorPosition(28, 4);
        Console.Write("Surname");

        int topOffset = 6;

        string currentLine = fileContent.ReadLine();

        while (!string.IsNullOrWhiteSpace(currentLine))
        {
            string firstName = currentLine.Split(' ')[0];
            string lastName = currentLine.Split(' ')[1];

            Console.SetCursorPosition(10, topOffset);
            Console.Write(firstName);
            Console.SetCursorPosition(28, topOffset);
            Console.Write(lastName);

            topOffset += 2;
            currentLine = fileContent.ReadLine();
        }

        fileContent.Dispose();

        Console.ReadLine();

This is not the best solution and your file might differ from this format. Well, now it's your turn to write code.

于 2013-03-19T18:21:59.907 回答
0

当您的评论说您正在写作时,您正在从文件流中读取,而当您的评论说您正在阅读时,您正在写作。您永远不会将读取的数据放入控制台流中。

此外,您将文件流的整个读取行,一次一个放入文件名,然后将其写回同一个流......在那里并不可取。

于 2013-03-19T18:02:58.000 回答