Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

* * * * * 1 votes

C for Beginner -- Part5: Basics of IO

c c for beginner input output scanf getchar

  • Please log in to reply
2 replies to this topic

#1 kernelcoder


    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 990 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal

Posted 06 March 2013 - 02:08 AM

Today we are going to learn about the most important part of programming --input/output. Here we will discuss about input from standard input device(the keyboard). This part of this tutorial will explain how to take input from user from the standard input device -- the keyboard.



Build-in Functions 

Functions are snippet of codes that performs some specific tasks on some given data. Built-in functions are similar to operational codes, they perform operations on given data. Those functions can be used in expressions. The syntax of built-in functions is:

return_type function-name ( argument{:argument...}){
//codes to do something on the data found in argument
Arguments for the function may be variables, constants, expressions, a prototyped procedure, or other functions. An expression argument can include a built-in function. In C language there are lots of built in functions located in various header files , we call those as library function. In C each function must return a value, if there is nothing to return then it will return void. The printf() returns void, the main returns void as we used void main so far. Simple calling to a function in a program:
printf(arguments);//printf as a built-in function
Input Characters
The standard library provides several functions for reading or writing one character at  a time, of which getchar and putchar are  the simplest. Each time it is called, getchar reads the  input character from a standard input device and returns its value.  The characters normally come from the keyboard. As we knew earlier a character can be shown in screen by %c in the printf() function. The function  getchar() waits until a character is pressed by the user.

char a;
printf(“Please Enter a charecter:”);
a = getchar();//try with pressing many characters but this will store only the first one
printf(“\n You have pressed character a :  %c”,a);

Here we used getchar() to take a character input. When the program starts running, the printf() shows  the message: “Please Enter a character:”  then getchar() waits until a key is pressed (will terminate taking input when the 'Enter' key is pressed) when a key is pressed it stores the character to the variable a. Finally we just printed the character in the screen. Showing some messages like those is a good programming practice. We have printed the character got from the getchar() function, we can also see the ASCII code of that character by printing the character as integer

printf(“\n You have pressed character a :  %c and ASCII Code is : %d”,a,a);

A character is nothing but an integer that represents the ASCII code of that character. For example see the program

int a = 65;
putchar(a);//same as printf("%c",a); notice that a is integer type

See the output of this program will show the character 'A' in the screen. The function putchar() prints a character each time it is called,  prints the contents of the  variable a as a character, usually on the screen. Calls to putchar and  printf may be interleaved,  the output will appear in the order in which the calls are made.

The scanf() Build-in Function
The scanf() is a build in function from header file stdio.h and is mostly used for user input. scanf( ) is the general -purpose console input routine. It can read all the built-in data types and automatically convert numbers into the proper internal format. It is much like the reverse of printf( ). The format for scanf( ) is
int  scanf(const  char  *control_string,  .  .  .  );
The scanf( ) function returns the number of data items successfully assigned a value. If an error occurs, scanf( ) returns EOF(ends of file). The control_string determines how values are read into the variables pointed to in the argument list.
The control string consists of three classifications of characters(same as format specifiers):
  •  Format specifiers, White-space characters & Non-white-space characters
The input format specifiers are preceded by a % sign and tell scanf( ) what type of data is to be read. The format specifiers are matched, in order from left to right, with the arguments in the argument list. Here's  some examples to take various types of input.
int a;
printf("\n the data you given : %d",a);
Please run this program several  times and input different types of data each time. Notice that this scanf waits until a 'Enter' key is pressed, when you input a character(=that means not a number type) the printf will show a garbage data(an undefined, not meaningful data). The scanf( ) function stops reading a number when the first non-numeric character is encountered.
To read an integer, we use either the %d or %i specifier. To read a floating-point number represented in either standard or scientific notation, we use %e, %f, or %g. (C99 also includes %a, which reads a  floating-point number.)
Here's some lists of specifiers
%a Reads a floating -point value (C99 only).
%c Reads a single character.
%d Reads a decimal integer.
%i Reads an integer in either decimal, octal, or hexadecimal format.
%e Reads a floating -point number.
%f Reads a floating -point number.
%g Reads a floating -point number.
%o Reads an octal number.
%s Reads a string.
%x Reads a hexadecimal number.
%p Reads a pointer.
%n Receives an integer value equal to the number of characters read so far.
%u Reads an unsigned decimal integer.
%[ ] Scans for a set of characters.
%% Reads a percent sign.

To read an individual character we used getchar( ), we can use scanf( ) for this purpose if we use the %c format specifier. However, like most implementations of getchar( ), scanf( ) will generally line-buffer input when the %c specifier is used. This makes it somewhat troublesome in an interactive environment.

Although spaces, tabs, and newlines are used as field separators when reading other types of data, 

when reading a single character, white-space characters are read like any other character. For 

example, with an input of "a b" this code fragment

scanf("%c%c%c", &a, &b, &c);//a='a' b='space character' c='b'


  • Thus the scanf( ) function can be used to read a string(sequence of characters) from the input stream using the %s format specifier. Using %s causes scanf( )  to read characters until it encounters a white-space character(Space/Tab/Enter). The characters that are read are put into the character array(we will learn about array later on) pointed to by the corresponding argument, and the result is null(=a character: ASCII code is 0, represented as '\0') terminated. As it applies to scanf( ), a white-space character is either a space, a newline, a tab, a vertical tab, or a formfeed.
  char str[30];//str is a character type variable that has 30 consecutive  variables in it
  printf("Enter a string: "); 
  scanf(''%s", str);//notice there is no '&' 
  printf("Here's your string: %s", str);
The program responds with only the "hello" portion of the string input "hello there"
  • A non-white-space character in the control string causes scanf( ) to read and discard matching characters in the input stream. For example, ''%d,%d" causes scanf( ) to read an integer, read and discard a comma, and then read another integer. If the specified character is not found, scanf( ) terminates. If you want to read and discard a percent sign, use %% in the control string.Strings will be read into character arrays, and the array name, without any index, is the address of the first element of the array. So, to read a string into the character array str, you would use scanf("%s", str). In this case, str is already a pointer and need not be preceded by the & operator.
  • All the variables used to receive values through scanf( )  must be passed by their addresses. This means that all arguments must be pointers. Recall that this is how C creates a call by reference, which allows a function to alter the contents of an argument. For example, to read an integer into the variable count , you would use the following scanf( ) call:

scanf("%d", &count);
The getch()
As we used this funtion in each of our program. This function simply waits until a key is pressed but it returns void and dont stores the key pressed even it doesn't show what key is pressed,  that we used to show the output until user wanted to close it.
Displaying an Address
When we declare a variable, a segment of the system memory is supplied to store the value of the variable. The size of the block depends on the variable type. Sometimes we need to display  address of a variable, we can use %p. This format specifier causes printf( ) to display a  machine address in a format compatible with the type of addressing used by the computer. The next program displays the address of sample:
#include <stdio.h> 
void main(){ 
int sample;
  printf(''%p", &sample); 
See there is a '&' before the sample variable in the printf function. This notation is generally used to display addresses and for other types of notation we will learn later on. After learning the above tutorial a learner should be able to take floating point, double type data input, if further explanation needed feel free to ask. From today on we will have some tasks basis of the tutorial part.
  • Various types data input by scanf() and output by printf()
  • Taking multiple inputs in one scanf()
  • Testing the errors may occur regarding scanf()
  • Testing by wrong data input
  • Finding out the situation when input is failed using scanf() etc



  • 0

#2 Opcode


    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 87 posts
  • Location:Singapore
  • Learning:C, C++, (Visual) Basic, Python

Posted 13 March 2013 - 10:27 AM

Thanks dude this is helping me

  • 0

#3 PredragVukovic


    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Learning:C, C++, PHP

Posted 14 March 2013 - 03:01 AM

Thank you ,it was really helpful.

  • 0

Also tagged with one or more of these keywords: c, c for beginner, input, output, scanf, getchar

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download