1

基本上我需要有人帮助我或向我展示允许我从名为 c1.txt 的文件中读取名称和价格的代码。

这是我已经拥有的。

    TextReader c1 = new StreamReader("c1.txt");
        if (cse == "c1")
        {
            string compc1;
            compc1 = c1.ReadLine();
            Console.WriteLine(compc1);
            Console.WriteLine();
            compcase = compc1;
            compcasecost = 89.99;
        }

如何从文本文档中选择要读取的行也很棒。

4

3 回答 3

10

你还没有告诉我们文本文件的格式。我将假设以下内容:

Milk|2.69
Eggs|1.79
Yogurt|2.99
Soy milk|3.79

您也没有指定输出。我将假设以下内容:

Name = Milk, Price = 2.69
Name = Eggs, Price = 1.79
Name = Yogurt, Price = 2.99
Name = Soy milk, Price = 3.79

然后以下将读取这样的文件并产生所需的输出。

using(TextReader tr = new StreamReader("c1.txt")) {
    string line;
    while((line = tr.ReadLine()) != null) {
        string[] fields = line.Split('|');
        string name = fields[0];
        decimal price = Decimal.Parse(fields[1]);
        Console.WriteLine(
            String.Format("Name = {0}, Price = {1}", name, price)
        );
    }
}

如果您的分隔符不同,那么您需要将参数更改'|'为方法(在名为asString.Split的实例上调用)。Stringlineline.Split('|')

如果您的格式需要不同,那么您需要使用该行

String.Format("Name = {0}, Price = {1}", name, price)

如果您有任何问题,请告诉我。

于 2010-01-14T22:16:35.317 回答
0
    static void ReadText()
    {
        //open the file, read it, put each line into an array of strings
        //and then close the file
        string[] text = File.ReadAllLines("c1.txt");

        //use StringBuilder instead of string to optimize performance
        StringBuilder name = null;
        StringBuilder price = null;
        foreach (string line in text)
        {
            //get the name of the product (the string before the separator "," )
            name = new StringBuilder((line.Split(','))[0]);
            //get the Price (the string after the separator "," )
            price = new StringBuilder((line.Split(','))[1]);

            //finally format and display the result in the Console
            Console.WriteLine("Name = {0}, Price = {1}", name, price);
        }

它给出了与@Jason 的方法相同的结果,但我认为这是一个优化版本。

于 2010-01-14T23:15:35.760 回答
0

您还可以尝试使用解析助手类作为起点,例如http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class中描述的类。

于 2010-12-23T18:43:02.357 回答