I have a doubt regarding using getchar()
to read a character input from the user.
char char1, char2;
char1 = getchar();
char2 = getchar();
I need to get 2
chars as inputs from the user. In this case, if the user enters the character 'A'
followed by a newline
, and then the character 'B'
, what will be stored in char2
- will it be the newline character or the character 'B'
?
I tried it on CodeBlocks on Windows, and char2
actually stores the newline character, but I intended it to store the character 'B'
.
I just want to know what the expected behavior is, and whether it is compiler-dependent? If so, what differences hold between turbo C and mingW?
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.
A getchar() reads a single character from standard input, while a getc() reads a single character from any input stream. It does not have any parameters. However, it returns the read characters as an unsigned char in an int, and if there is an error on a file, it returns the EOF at the end of the file.
The getchar() function returns an integer which is the representation of the character entered. If you enter the character A , you will get 'A' or 0x41 returned (upgraded to an int and assuming you're on an ASCII system of course).
getchar() has no parameters. Every time you call it, it reads the next character of input and returns it to you. The function returns an int, being the ASCII code of the relevant character, but you can assign the result to a char variable if you want.
Yes, you have to consume newlines after each input:
char1 = getchar();
getchar(); // To consume `\n`
char2 = getchar();
getchar(); // To consume `\n`
This is not compiler-dependent. This is true for all platforms as there'll be carriage return at the end of each input line (Although the actual line feed may vary across platforms).
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