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 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 ??
getchar() is a function that reads a character from standard input. EOF is a special character used in C to state that the END OF FILE has been reached. Usually you will get an EOF character returning from getchar() when your standard input is other than console (i.e., a file).
If the stream is at end-of-file, the end-of-file indicator is set, and getchar() returns EOF. If a read error occurs, errno is set, and getchar() returns EOF.
getchar function takes input from stdin character by character. its stored in a variable c. &that's compared with EOF. EOF stands for END OF FILE. we use this while reading characters from a file.
getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C. It is included in the stdio. h header file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With