How to Read and Write a Character (or) String without using Scanf (or) Printf Statements

Reading a Character:

Reading a single character from the keyboard can be done by using  the functions getchar.

Syntax:  variablename = getchar();

variablename is a valid C name that has been declared as char type. When this statement is encountered the computer waits untill a key is pressed and * then assigns this character as value to getchar function.

Ex: char name;
       name = getchar();

getchar is used on the right–hand side of an assignment statement  the value of getchar is in turn assigned to the variable name on the left.

The getchar function may be called successively to read the characters contained in a line of text. For ex, the following program segment reads characters from keyboard one after another until the return (\n) key is pressed.

-----
char ch;
ch=' ';
while(ch!=’\n’)
{
ch=getchar();
}
- - -

Ex:– program for enter a character from keyboard and check whether it is an alphabet or digit or any other special symbol.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
printf(“press any key”);
ch=getchar();
if(isalpha(ch)>0)
printf(“character is a letter”);
else
if(isalpha(ch)>0)
printf(“character is digit);
else
printf (“character is not alphanumeric”);
getch();
}

Writing a character:

Like getchar there is another function putchar for writing characters one at a time to the terminal.

Syntax: putchar( variablename);

Where  variablename is a type char var containing a characters. This statement displays the character contained in the  variablename.

Ex:–     result = ‘p’;
            putchar(‘\n’); used to more the cursor on the screen to the beginning of next  line.

Related

C Language 2778456298367935583

Post a Comment

emo-but-icon

item