Function: Put char Function and Gets Function, Some More Functions

Get unlimited access to the best preparation resource for IAS : fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 194K)

Image of getchar() and putchar() functions

Image of Getchar() and Putchar() Functions

Put Char () Function

  • The put char () function takes one argument, which is the character to be sent to output device.

  • It also returns this character as a result. The general form of the put char () function is:

put char (ch).

Where ch is a variable of type character

Example-1

# include < iostream.h >

# include < stdio.h>

void main ()

{

char ch.

ch = get char ().

put char (ch).

}

The above program takes a character from the keyboard and prints it on the screen.

Gets () Function

  • The gets () function gets a string terminated by a newline character from the standard input stream stdin.

  • The gets () replaces the newline by a null character (\0). It also allows input string to contain white space characters (spaces, tabs), gets return when it encounters a newline; everything up to the newline is copied into A.

gets (A).

Example 2

# include < stdio.h >

# include < iostream.h >

void main ()

{

char A [100].

cout << “Input a string”.

gets (A).

puts (A).

}

Some More Functions

The Getch () and Getche () Functions

The general form of the getch () and getche () is

ch = getche ().

ch1 = getch ().

  • ch and ch1 are the variables of type character.

  • They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character. The value of the character returned from getche () is assigned to ch.

  • The getche () function echoes the character to the screen.

  • That's why there's an e in getche. Another function, getch (), is similar to getche () but does not echo the character to the screen.

Example 3

To count the no. of characters and words in a sentence entered by the user.

# include < iostream.h >

# include < conio.h >

void main ()

{

char ch.

int chcnt = 0, wdcnt = 1.

while ((ch = getche ()) ! = ‘\r’)

{

if (ch = = ‘’)

wdcnt + +.

else

chcnt + +.

}

cout < < “No. of characters” < < chcnt << “\n”

cout < < “No. of words” < < wdcnt.

}

The above program counts the no. of characters and no. of words in a sentence terminated by return key. The ‘\r’ reads the return key character.

Developed by: