开发者

(c = getchar()) != EOF in C#?

What is the C# equivalent of the following C code:

while((c = getchar())!= EOF)
   putchar(c);

I know getchar() and putchar() are going to be replaced by Console.Read 开发者_JAVA技巧and Console.Write respectively but what about the EOF. Especially keeping in mind, C# works with unicode and C with ASCII, what are the implications of that ??


Console.Read() returns -1 on EOF (coincidentally, EOF is defined as -1 on most platforms).

You can do:

int c;
while ((c = Console.Read()) != -1) {
   Console.Write(Convert.ToChar(c));
}

Also, C# works natively with UNICODE in the same way that C works natively with ASCII, i.e. there are no more implications. System.Char represents an UCS-2 UNICODE character, which also fits into an int, so everything will be all right.


Off the top of my head,

int c; // N.B. not char
while((c = Console.In.Read()) != -1)
    Console.Out.Write((char)c);

Apparently Read() returns -1 if there's nothing more to read. I don't see an EOF constant defined. I might be inclined to use >= 0 instead of != -1 even.

I don't think ANSI vs Unicode makes any difference - you're reading a number from one API call and feeding it into the other. You can use Unicode in C too.


        int c = -1;
        while ( (c =Console.Read()) >=0)
        {
            Console.WriteLine(c);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜