scanf() to input data from keyboard

We can pass data to our C program by using scanf() function. Once executed our program will wait for the user inputs once it came across any scanf function during program execution. Let us enter an integer value and then display the same value by using printf function.
#include <stdio.h>
int main(void){
int num;
	printf("Enter a number  ");
	scanf("%d",&num);
	printf(" You entered %d", num); // printing outputs
return 0;
}
While using scanf() , before using the variable we will use & ( ampersand ) to indicate to store the data in address of the variable. See the &num to say store the input data in address of our variable num.

As you have seen we will get the same data as output what we enter as input.

Entering more than one data

Using one scanf statement we can ask for more than one data to enter
int main(void){
int num1,num2; // declaring variables as integers
	printf("Enter the  two numbers  ");
scanf("%d %d",&num1,&num2);  // Enter two numbers
printf(" Two numbers are %d,%d  " ,num1, num2); // printng outputs
return 0;
}
Note that after entering first number we have to press Enter and then write the second number.

Reading String data

Here is the code to read string data. Note that scanf function will read until it encounters any space or it reaches its limits.
int main(void){
char name[30];
	printf("Enter your name  ");
	scanf("%s",name);
	printf(" Welcome Mr %30s", name); // printing outputs
return 0;
}
We will read more on scanf in our string handling section for handling other type of data.
%c  - a single character
%d  - a decimal integer 
%e - floating point value
%f - floating point value
%g - floating point value
%h - short integer
%i - floating point value
%o - an octal intger
%s - read a string
%u - unsigned decimal integer
%x - read a hexadecimal integer
%[..] - string of words
With the above list we can prefix these chars in some cases
h for short integers
l for long integers or double
L for long dobule
Basic programming structure of C

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Arjun khatiwada

    28-01-2013

    Plz ,says me limitation of putchar and getchar functions for reading strings

    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer