Sunday 16 May 2021

String Input and Output functions in C language

Reading string from terminal

a) Using scanf function: The familiar input function scanf can be used with ‘%s” format specification to read a string of characters.

Example: char address[10];

scanf(“%s”, address);

b) Reading a line of Text: C supports a format specification known as the edit set conversion code %[^\n] that can used to read a line containing a variety of characters, including white spaces.

Example: char address[10];

scanf(“%[^\n]”, address);


c) Using getchar and gets functions:

getchar function: used to read a single character from the terminal. We can use this function to repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the new line character (‘\n’) is entered and the null character is then inserted at the end of the string.

Example: char ch;

ch=getchar();

gets function: It reads all characters from terminal into string until null character encountered.

Example: char line[80];

gets(line);

prints(“%s”, line);

Writing strings to screen:

a) Using printf function: we have used extensively the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character.

For example, the statement

printf(“%s”, name);

can be used to display the entire contents of the array name.

b) Using putchar and puts functions:

The putchar function is used to output single character. It takes the following form

Example: char ch=”A”;

putchar(ch);

We can use putchar function to repeatedly to output a string of characters stored in an array using a loop.

Example: char name[6]=”PARIS”

for(i=0;i<5;i++)

putchar(name[i]);

If you want to display the entire string at a time use puts function.

Example: puts(name);

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top