Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification needed regarding getchar() and newline

Tags:

c++

c

getchar

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?

like image 518
Raj Avatar asked Sep 22 '12 13:09

Raj


People also ask

What does the getchar () function do?

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.

How many characters does function getchar () read?

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.

Does Getchar work with integers?

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

Does Getchar return ascii value?

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.


1 Answers

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

like image 148
P.P Avatar answered Sep 24 '22 22:09

P.P