IOStream operator<< Conversion from C++ to C#

前端 未结 3 595
闹比i
闹比i 2021-01-29 13:08

I am trying to convert some old C++ code to C# and having difficulty in understanding what the following code does and how can it be converted into C#.

ifstream         


        
相关标签:
3条回答
  • 2021-01-29 13:28

    This has probably slightly different semantics from the C++ code, but should be relatively similar:

    IEnumerable<string> ReadWhiteSpaceSeparated(string filename)
    {
        using(var lines = File.ReadLines(filename))
        {
            return lines.SelectMany(line => line.Split(new []{' ','\t', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries));
        }
    }
    
    IEnumerable<string> ReadDoubles(string filename)
    {
         return ReadWhiteSpaceSeparated(filename)
             .Select(s => double.Parse(s, CultureInfo.InvariantCulture));
    }
    

    Then you can read count doubles from a file with ReadDoubles(filename).Take(count)

    0 讨论(0)
  • 2021-01-29 13:30

    In this situation the >> operator is streaming data from the file stream into what I assume is a double. Here is how the code would look in C# (change the 8 to a 4 if you're just using a float):

    using (var stream = System.IO.File.Open(file, System.IO.FileMode.Open))
    { 
        var data = new byte[8]; // temp variable to hold byte data from stream
        for(var x = 0; x < count; ++x)
        {
            stream.Read(data, 0, 8);
            num = System.BitConverter.ToDouble(data, 0); // convert bytes to double
            // do something with num
        }
    }
    
    0 讨论(0)
  • 2021-01-29 13:37

    The C++ Standard Library overloads the bitshift operators (<< and >>) to mean "write to stream" and "read from stream", respectively. In this case, fin is a file stream; fin >> num means to read from the file (until the next whitespace character), parse the data to match the format of the variable num (an integer), and store it into num.

    0 讨论(0)
提交回复
热议问题