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
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)
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
}
}
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
.