Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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 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 ??

like image 971
Fahad Avatar asked Nov 18 '10 12:11

Fahad


People also ask

What is Getchar and EOF in C?

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).

Does Getchar read EOF?

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.

What is EOF in Getchar?

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.

What does getchar () do in C?

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.


2 Answers

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.

like image 192
Frédéric Hamidi Avatar answered Oct 20 '22 10:10

Frédéric Hamidi


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.

like image 44
Rup Avatar answered Oct 20 '22 09:10

Rup