简体   繁体   English

如何使用 StreamReader 读取 C#.

[英]How to read C# . using StreamReader

I'm trying to read a string with StreamReader, so I don't know how to read it.我正在尝试使用 StreamReader 读取字符串,所以我不知道如何读取它。

using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace 
{
    class Program
    {
        static void Main(string[] args)
        {
            string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
            string payerCountInput = "8\n";
            string individualCostInput = "52.24\n";

           
                double individualCost = RestaurantBillCalculator.CalculateIndividualCost(reader2, totalCost);
                Debug.Assert(individualCost == 54.14);

                uint payerCount = RestaurantBillCalculator.CalculatePayerCount(reader3, totalCost);
                Debug.Assert(payerCount == 9);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;

namespace as
{
    public static class RestaurantBillCalculator
    {

        public static double CalculateTotalCost(StreamReader input)
        {

//  I want to read the input (not System.IO.StreamReader, 

25.34
10.99
250.22
21.87
50.24
15

//below is what i tried..
            int[] numbers = new int[6];
            for (int i = 0; i < 5; i++)
            {
                numbers[int.Parse(input.ReadLine())]++;

            }


            for (int i = 0; i < 5; i++)
            {
                    Console.WriteLine(numbers[i]);
            }


            return 0;
        }
       

        public static double CalculateIndividualCost(StreamReader input, double totalCost)
        {
            return 0;
        }

        public static uint CalculatePayerCount(StreamReader input, double totalCost)
        {
            return 0;
        }
    }
}

Even when I googled it, only file input/output came up with that phrase.即使当我用谷歌搜索时,也只有文件输入/输出出现了那个短语。

I want to get a simple string and read it.我想得到一个简单的字符串并读取它。

int[] numbers = new int[6]; // The number at the index number

// take the given numbers
for (int i = 0; i < n; i++)
{
    numbers[int. Parse(sr. ReadLine())]++;
}

I tried the above method, but it didn't work.我试过上面的方法,但是没有用。

I just want to get the index and read the contents of itemCostsInput as it is.我只想获取索引并按原样读取itemCostsInput的内容。 If I just execute Console.writeLine, String == System.IO.StreamReader如果我只是执行Console.writeLine, String == System.IO.StreamReader

comes out I want to read and save the values of itemCostsInput respectively.出来我要分别读取和保存itemCostsInput的值。 I just want to do something like read.我只想做一些阅读之类的事情。

I'm sorry I'm not good at English对不起,我英语不好

I expected input Read我期待输入阅读

25.34
10.99
250.22
21.87
50.24
15

but console print System.IO.StreamReaderconsole print System.IO.StreamReader

This lines are the ones causing (more) trouble I think:我认为这些行是造成(更多)麻烦的行:

        for (int i = 0; i < 5; i++)
        {
            numbers[int.Parse(input.ReadLine())]++;

        }

Should be应该

        for (int i = 0; i < 5; i++)
        {
            numbers[i] = int.Parse(input.ReadLine());

        }

But since you have a decimal input (in string format due to the streamreader), maybe numbers should be an array of decimals.但是由于您有一个小数输入(由于流阅读器而采用字符串格式),因此数字可能应该是一个小数数组。

Also there are quite a few remarks about the use of StreamReader, since if the file doesn't have 5 or more lines, your program will also break.还有很多关于 StreamReader 使用的评论,因为如果文件没有 5 行或更多行,您的程序也会中断。 I let this here hoping will clarify something to you, though我把这个放在这里希望能向你澄清一些事情,不过

Your code does not make sense in its current state.您的代码在其当前的 state 中没有意义。
Please read up on Streams .请阅读Streams

Usually you'd get a stream from a file or from a.network connection but not from a string.通常你会从一个文件或一个网络连接中得到一个 stream 而不是从一个字符串中。
You are confusing integer and double.您混淆了 integer 和 double。
The double data type represents floating point numbers. double数据类型表示浮点数。

It seems to me that you just started programming and are missing out on most of the fundamentals.在我看来,您刚刚开始编程并且错过了大部分基础知识。

First, convert your string input into a stream:首先,将您的字符串输入转换为 stream:

static System.IO.Stream GetStream(string input)
{
    Stream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(input);
    writer.Flush();
    stream.Position = 0;

    return stream;
}

Now you can convert your input to a stream like this:现在您可以像这样将输入转换为 stream:

// ... code ...

string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
var dataStream = GetStream(itemCostsInput);

// ... code ...

Now you that you converted your string input into a stream you can start to parse your data and extract the numbers:现在您已将字符串输入转换为 stream,您可以开始解析数据并提取数字:

static List<double> GetDoubleFromStream(Stream stream)
{
    if (stream == null) {
        return new List<double>();
    }

    const char NEWLINE = '\n';

    List<double> result = new List<double>();
    using (var reader = new StreamReader(stream)) 
    {
        // Continue until end of stream has been reached.
        while (reader.Peek() > -1) 
        {
            string temp = string.Empty;
            // Read while not end of stream and char is not new line.
            while (reader.Peek() != NEWLINE && reader.Peek() > -1)  {
                temp += (char)reader.Read();
            }
            // Perform another read operation 
            // to skip the current new line character
            // and continue reading.
            reader.Read();

            // Parse data to double if valid.
            if (!(string.IsNullOrEmpty(temp))) 
            {
                double d;
                // Allow decimal points and ignore culture.
                if (double.TryParse(
                    temp, 
                    NumberStyles.AllowDecimalPoint, 
                    CultureInfo.InvariantCulture, 
                    out d)) 
                {
                    result.Add(d);
                }
            }
        }
    }
    return result;
}

This would be your intermediate result: Now you can convert your input to a stream like this:这将是您的中间结果:现在您可以将输入转换为 stream,如下所示:

// ... code ...

string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
var dataStream = GetStream(itemCostsInput);
var result = GetDoubleFromStream(dataStream);
// ... code ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM