DevonJ901 DevonJ901 - 16 days ago 6
C# Question

Stream Right Shift Operator Equivalent In C#?

I was trying to convert a class from C++ to C# and have encountered two errors with the Binary Right Shift Operator '>>'.

This is the orignal C++ code converted to C# (without editing):

public static void ReadSeatPrices()
{
ifstream fin = new ifstream();
fin.open("SeatPrices.txt");
int i = 0;
while (fin != null)
{
fin >> seatprices[i];
i++;
}
fin.close();
}


When compiling the class in Visual Studio 2015 multiple errors occurred at first due to
ifstream
, so naturally I edited the code to remove these errors and now it looks like this:

public static void ReadSeatPrices()
{
FileStream fin = new FileStream("seat.txt", FileMode.Open,
FileAccess.Read);
int i = 0;
while (fin != null)
{
fin >> seatprices[i];
i++;
}
fin.Close();
}


Now I am left with two errors which is caused by this line:

fin >> seatprices[i];


The error list output states that:


"Operator '>>' cannot be applied to operands of type 'FileStream' & 'Double'

Only assignment, call, increment, decrement, and new object expressions can be used as a statement.


Is there some sort of equivalent operator which I must use instead in C#? I Would appreciate if someone could help me understand my mistake.

Answer
public static void ReadSeatPrices() {
    using (var reader = new StreamReader(File.OpenRead("seat.txt"))) {
        int i = 0;
        while (!reader.EndOfStream) {
            var double result;
            if (double.TryParse(reader.ReadLine(), out result)) {
                seatprices[i] = result;
                i++;
            } else {
               //something goes wrong
            }
        }
    }
}

Use TryParse() if you can't garantee that conversion is possible. If yor're sure that conversion is ever works, so you can eliminate if and use just Parse().

You shold use ReadLine() method form StreamReader (right class to do the job) to read a stream. C# doesn't have >> operator overload for this.

Use using. C# doesn't have automatic RAII.

Translate code from one language to another doesn't work one to one, you need to find the right idiom.