Search code examples
c#inputcharint32textreader

C#. How come when I use TextReader.Read() it returns an int value? Possible to convert to char?


So TextReader.ReadLine() returns a string, but TextReader.Read() returns an int value. This int value also seems to be in some sort of format that I don't recognize. Is it possible to convert this integer to a character? Thanks for any help.

EDIT:

TextReader Values = new StreamReader(@"txt");

    string SValue1;
    int Value1;       
    Value1 = Values.Read();        
    Console.WriteLine(Value1);
    Console.ReadKey();

When it reads out the value it gives me 51 as the output. The first character in the txt file is 3. Why does it do that?


Solution

  • According to the documentation for the StringReader class (a sub-class of TextReader), the return value of Read() can be converted to a char, but you need to check if you're at the end of file/string first (by checking for -1). For example, in this modified code from the documentation:

    while (true)
    {
        int integer = stringReader.Read();
    
        // Check for the end of the string before converting to a character.
        if (integer == -1)
            break;
    
        char character = (char) integer; // CONVERT TO CHAR HERE
    
        // do stuff with character...
    }