2017-11-01 16:54:28
C++ / C#
, 2017-11-01 16:54:28

After reading the file, the values ​​\u200b\u200bof the file are added, the output is an unexpected result, can we smell it?

class Program
    {
        static void Main(string[] args)
        {

            string name_inp_f = "input.txt";
            double c1 = 0;
            double c2 = 0;
            ;

            FileStream inp_f = new FileStream(name_inp_f, FileMode.Open);

            StreamReader reader_f = new StreamReader(inp_f);

            while (reader_f.Peek() != -1)
            {
                char c = (char)reader_f.Read();
                c1 = Convert.ToInt32(c);          
                c = (char)reader_f.Read();
                c2 = Convert.ToInt32(c);
            }

            c1 += c2;
            Console.WriteLine(c1);
            Console.ReadKey();

        }
    }

The file contains the number 1 and 3 (there is a space between 1 and 3). the program was expected to read them and place them in variables C1 and C2. after that, addition should occur and output the result to the console. But in the end, instead of 4, I get 65589. Why? (The purpose of all this is to understand how to work with files and their nuances)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cicatrix, 2017-11-01
Georgy Voronko @

StreamReader by default opens a file in UTF-8 encoding and considers that there are 2 bytes in one character.
You must explicitly specify the file encoding in the initialization of the StreamReader.
And in general, it would be good practice to read the line (ReadLine), then parse it.
And, as I already pointed out in the comment, casting Char to Int32 will return the character code, not the string value.
In order to turn the character "3" into the number 3, you need to use the Parse method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question