Friday 23 August 2013

C Programming beginners, Read Value from user in string

Reading value in string from user and display it in format

1)Read Single Character
#include<conio.h>
#include<stdio.h>
void main()
{
char str1;
clrscr();
printf("Enter Your Name:");
scanf("%c",&str1);
printf("\n\nYou have entered:%c",str1);
getch();
}
O/P:


2) Read Single Word
#include<conio.h>
#include<stdio.h>
void main()
{
char str1;
clrscr();
printf("Enter Your Name:");
scanf("%s",str1);//Read single word
printf("\n\nYou have entered:%c, ",&str1);//It will give some random Char
printf("\n\nYou have entered:%s",str1);//This will display Single Word
getch();
}
O/P:



3)Read Sentence
#include<conio.h>
#include<stdio.h>
void main()
{
char str1;//Store 2 byte data
clrscr();
printf("Enter Your Name:");
scanf("%[^\n]",str1);//Read single word
printf("\n\nYou have entered:%s",str1);
getch();
}
O/P:
This will read only 1 byte data. and more than 1 byte will result into garbage.


4)To overcome problem of above program string pointer is used.
in this program instead of char str1 we'll use pointer to read complete string
and it is declared  as char *str1, now it hold no. of bytes. and to read complete sentence we'll use
%[^\n].

#include<conio.h>
#include<stdio.h>
void main()
{
char *str1;
clrscr();
printf("Enter Your Name:");
scanf("%[^\n]",str1);//Read single word
printf("\n\nYou have entered:%s",str1);
getch();
}
O/P:

No comments:

Post a Comment

Contact Form

Name

Email *

Message *