5

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?

Alexander
  • 53
  • 1
  • 4

3 Answers3

2

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

The documentation tells you: it returns -1 if there is no more data to read, and otherwise it returns the character, as an integer. The integer is not "in some sort of format"; integers are raw data. It is, rather, characters that are "formatted"; bytes on the disk must be interpreted as characters.

After checking for -1 (which is not a valid character value and represents the end of stream - that's why the method works this way: so you can check), you can convert by simply casting.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
2

Read returns an int o that end-of-stream (-1) can be detected. Yes, you just cast the result to a char as in var c = (int) reader.Read();.

Typical usage:

while (true)
{
    int x = reader.Read();
    if (x == -1) break;
    char c = (char) x;
    // Handle the character
}
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73