Monday, August 20, 2018

Basic Input Output




Getting information in and out of a computer is the most important thing that a program can do. Without input and output computers would be quite useless.
C treats all its output as though it were reading or writing to different files. A file is really just an abstraction: a place where information comes from or can be sent to. Some files can only be read, some can only be written to, others can be both read from and written to. In other situations files are called I/O streams.

Three standard files: stdin, stdout & stderr

C has three files (also called streams) which are always open and ready for use. They are called stdin, stdout and stderr, meaning standard input and standard output and standard error file. Stdin is the input which usually arrives from the keyboard of a computer. stdout is usually the screen. stderr is the route by which all error messages pass: usually the screen. This is only `usually' because the situation can be altered. In fact what happens is that these files are just handed over to the local operating system to deal with and it chooses what to do with them. Usually this means the keyboard and the screen, but it can also be redirected to a printer or to a disk file or to a modem etc. depending upon how the user ran the program.
The keyboard and screen are referred to as the standard input/output files because this is what most people use, most of the time. Also the programmer never has to open or close these, because C does it automatically. The C library function covered by stdio.h provides some methods for working with stdin and stdout. They are simplified versions of the functions that can be used on any kind of file. In order of importance, they are:
 printf ()
 scanf  ()
 getchar()
 putchar()
 gets   ()
 puts   ()

Types of I/O

Almost every programming language handles program input/output (I/O) differently. However, what are common to most programming languages are the two types of I/O: user I/O and file I/O.

User I/O

User I/O is interactive since this type of input is generally accomplished via the keyboard or mouse and a monitor. A typical scenario for user I/O is a prompt on the computer monitor asking a user for some needed information. Once this information is entered, the program assigns the input to a variable and continues its execution. A very common prompt for user input and output is called a command prompt.

File I/O

Often there are times when we need to give input to a program that does not need to be interactive. For example, suppose we had a program that calculated the grades for a class with 200 students. If the program prompted us to enter the grade for each student, we would quickly grow bored and give up. Instead what we would like to do is collect all the information in one place and allow the program to read what it needs from that location rather than asking us for the data. The solution to our problem is file I/O.
File I/O allows us to store data in a file on the computer and then read the data from this file. This type of input is not interactive since the computer does not wait for a response from the user. Instead, the data is read directly from a file specified in the program. Notice how this is different from user I/O. With user I/O, the program halts each time it reaches an input statement. Execution cannot continue until the program receives a response from an input device like the keyboard. However, file I/O allows the computer to get the input for itself without the help of the user so the program does not need to halt at each input. This makes file I/O ideal for processing large amounts of data at once.
As with user I/O, file I/O, typically done using a collection of procedures that are defined by a given programming language. Of course, these procedures will need an extra parameter that tells them which file to use for input or output. Since these details are also very languages specific, they are not covered in this lesson.

Code it or buy it

A C program contains one or more functions, which are a code blocks meant to perform a specific task.  Many commonly needed functions are already write and compiled for the user in the function library supplied with every C compiler. Instead of writing the individual instructions, user just tells the compiler to use one of its standard functions. When user wants to perform a task that is not in the library, he needs to write his own function.
The basic input and output tasks are carried out by using library functions available from standard GCC library. The stdio.h [standard input output] file must be included before using any basic Input/Output functions in a code and is done by writing below statement.
#include <stdio.h>
The directive #include tells the compiler to add this stdio.h from default standard library folder to current code file.
Note again that standard I/O refers to the most usual places where data is either read from, the keyboard, or written to, the video monitor. Since they are used so much, they are used as the default I/O devices and do not need to be named in the Input/Output instructions.

Single Character input

There are two library functions called: un buffered getch() and buffered getchar() used to get single character input from user or file. Both functions return ASCII values, which is of integer type, but can be assign to char type also to detect the character.  Also note that both functions works with user input and with file input.
Usually both functions can be used to pause the program at certain stage and after any key press to do the next instruction.
The getch() function is un buffered function, hence does not echo the user input on screen and return key press directly for manipulation purpose. Below code lines detect Enter key press and exit and no echo of key press is observed here. Note that integer type variable is used for storing key press value.
int keypress;
printf(“Press Enter Key to exit…\n”);
keypress = getch();
if(keypress == 27)
exit();
The getchar() function is buffered function, and it does echo the user input on screen and then stored key press value is used for manipulation purpose. Below code lines detect ‘y’ key press, displays it and then exit. Note that char type variable is used for storing response value.
char response;
printf(“Do you want to exit? Press ‘y’ for yes …\n”);
response = getchar();
if(response == ‘y’)
exit();

Single Character output

There is one function called: putchar(), a buffered one to output single character on output device / screen.  The function converts the variables value to equivalent ASCII character and sends it to output device. The function putchar()  takes single character between single quote as its argument.
Best example of using this function is at login screen where password is asked from user. In such condition single character is to be outputted to the screen [or file] for proper operation.
for ( int i = 0; i<4 ; i++)
  {
password[i]=getchar();
putchar(‘\b’); putchar(‘*’);
}             
This function is also used with for loop to read whole text file for copying purpose.

String or line Input

What if the programmer wants a function that will retrieve a newline-terminated string from the console or a file. In other normal words, it must reads a line of text. Then comes the gets() library function in action.
The function gets all data entered including white spaces until enter/return key pressed, appends a null character ‘\0’ and assign it to storing variable.
char text[10];
printf (“Enter your name …\n”);
gets(text);

String or line output

If code needs string output on output device / screen, programmer can use library function puts(). The function sends whatever is in between double quotes [“ “] to output device. This function is used where only text or string line is to be printed on standard output device. Actually it output a NUL-terminated string.
char text[10] = “M.K.Gandhi”;
puts(text);
puts(“Bye-bye, take care.”);
The of puts() function accepts character array or direct quoted strings as its arguments and prints it on new line. Since you do not need to include a newline character puts does that for you. This function is simple, safe but not very flexible because it puts unformatted output to screen or text stream stdout.

Formatted input

Usually the programs needs to scan user input for mixed data types, for example age as integer data type, weight as float number and gender as character type. And such input are scanned by scanf() function with proper conversion string. This scanf() function allows user to enter different type of data as input for manipulation.
The scanf() function’s general form is :
scanf ( “ conversion string “ , variable_list );
Note that scanf() obviously needs a pointer to the variable if it is going to change the variable itself, so we use the address-of operator to get the pointer.
What means formatted input? Suppose code has variable which stores age of user, and it is to be scanned from user then this function comes in action.
int age;
scanf(“ Enter you are age:  “, &age );
/* in above code line age stores user entered value. Note that it uses & sign with age to indicate store scanned value into its address*/

So to scan integer type data %d is used, for float %f and for character %c is used. There still many conversion specifier available for coder to use them in his code are: %u for unsigned integer, %e floating point with exponential and %s for string variable.
How about scanning mixed data type information from user input?
int age; char gender; float weight;
printf ( “ Enter age, gender and weight: “ );
scanf(“ %d, %c, %f  “, &age , &gender, &weight);
/* above code line scans three variables and stores them in specific address */

The scanf() is famously sensitive to programmer errors. If scanf() is called with anything but the correct pointers after the format string, it tends to crash or otherwise do the wrong thing at run time.

Formatted output

Sometime programs need formatted output, such as stored variable values or database contents to display on standard output device and is achieved by using printf() function. The printf() function gives the user control over how text and numerical data are to be laid out on the screen. The function helps print good looking data or string to user perusal in available space.
The printf() function’s general form is :
printf ( “ conversion string “ , variable_list );
What means formatted output? Suppose code has variable which stores age of user, and it is to be printed then this function comes in action.
int age;
age = 20;
printf(“ you are %d years old! “, age );
/* above code line prints: you are 20 years old! */
So to print integer type data %d is used, for float %f and for character %c is used. There still many conversion specifier available for coder to use them in his code are: %u for unsigned integer, %e floating point with exponential, %s for string and %p for pointer variable.
How about printing mixed data type information to user screen?
int age; char gender; float weight;
age = 20; gender = ‘M’; weight = 58.5;
printf(“ Age: %d years \t Gender: %c\t Weight: %f \n “, age , gender, weight);
/* above code line prints:
Age: 20 years   Gender: M Weight: 58.5
 */

Sometimes code needs clean formatted output with different data type variables; in such case modifiers are used.
Printf() function with modifiers
printf ( “ % - w . p Sp “ , variable_name ) ;
where
-      left justification
w   width
.  precision separator
p  precision
Sp conversion specifier
Print a formatted string to the console or to a file.
Note that if the conversion specifier do not match the number and type of arguments, printf() tends to crash or otherwise do the wrong thing at run time.

Formatted Output to printer

If code needs hardcopy or printer output from its data, programmer can use library function fprintf().  Since printer is treated as file in LINUX, fprintf() stands for ’formatted print function for file’. This function is similar to printf() function, with additional argument stdprn’ for directing the output to printer rather than stdout or screen.
Example 4.8: Code segment showing usage of fprintf() where \t is tab and not printed on paper.
#include <stdio.h>

main()
{
char gender[3] = { 'M', 'M' , 'M' } ;
char name[3][6] = { "Tom", "Dick", "Harry" };
int rollnos[3] = { 111 , 112 , 113 };
float weight[3] = { 45.0 , 61.7 , 56.5 };

fprintf(stdprn, "Students Information Chart\n");
fprintf(stdprn, "Roll No  Name   Gender  Weight \n");
for(int i=0; i < 3; i++)
       fprintf(stdprn, "%d\t %s\t %c\t %2.2f\n", rollnos[i], name[i],                  gender[i], weight[i]);
fprintf(stdprn, "---------------------------\n");

}

$ ./a.exe
Students Information Chart
Roll No  Name   Gender  Weight
111   Tom    M   45.00
112   Dick    M   61.70
113   Harry    M   56.50
---------------------------

ASCII character set and Escape Sequences

In C programming language, there are 256 numbers of characters in character set. The entire character set is divided into 2 parts i.e. the ASCII characters set and the extended ASCII characters set. But apart from that, some other characters are also there which are not the part of any characters set, known as ESCAPE characters.
Escape Sequences or Control characters are invisible on the screen. They have special purposes usually to do with cursor movement. They are written into an ordinary string by typing a backslash character \ followed by some other character.
\[command or symbol]
Escape Sequence List
To insert
Escape Sequence
Beep or Alarm
New line
\a
\n
Horizontal Tab
\t
Vertical Tab
\v
Back space
\b
Carriage Return
\r
Form feed
\f
Back slash
\\
Double Quote
\”
Single Quote
\’
Question Mark
\?
Null character
\0

You can use escape sequences in formatted print functions, such as printf() or un-formatted print functions such as puts() alike. Because escape sequences are commands and hence treated as single character despite made by two symbols.
Example 4.9: Code segment showing usage of escape sequences.
main ()
{
putchar(‘A’);
putchar(‘B’);
putchar(‘\n’);
putchar(‘C’);

printf( “This is first line.” );
printf( “This is second line.\n” );
printf( “This is third line.” );

puts(“\n He said  \”God Is Great\”  “);
puts(“\n Roll No\t  Name\t\t  Address”);
puts(“\\n”);
}
Output:
AB
C
This is first line. This is second line.
This is third line.
He said “God Is Great”
Roll No  Name      Address
\n
Escape sequences are also used to represent certain special characters within string literals and character constants.

Invisible Null Character

The “ “ or empty string is actually not empty it contains null character. The ASCII Null Character or ‘\0’ is not zero but it is all bits are set to zero. In string, it helps the compiler to determine the actual end of the string. 


Previous Page Main Contents Next Page

No comments:

Post a Comment