Unit 4
Managing Input & Output Operations
- Explain Reading a Character and writing a character
When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.
The Standard Files
C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen.
Standard File | File Pointer | Device |
Standard input | Stdin | Keyboard |
Standard output | Stdout | Screen |
Standard error | Stderr | Your screen |
The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen.
The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen.
The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example −
#include <stdio.h>
Int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you want to use fgets().
#include <stdio.h>
Int main( ) {
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better −
#include <stdio.h>
Int main( ) {
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows −
$./a.out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like "string integer". If you provide "string string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for scanf().
2. Explain Various library functions from ctype.h
As string.h header file contains inbuilt functions to handle Strings in C/C++, the ctype.h/<cctype> contains inbuilt functions to handle characters in C/C++ respectively.
Characters are of two types:
- Printable Characters: The characters that are displayed on the terminal.
- Control Characters: The characters that are initiated to perform a specific operation.
The arguments passed to character functions should be of integer type. If we pass characters instead of an integer, the characters are typecasted into integers(corresponding ASCII values) and those integers are passed as arguments.
The below functions under ctype.h/<cctype> header file are applied on normal characters. Wide character functions are used for the characters of type wchar_t.
S.No | Function | Description | Return Values |
1. | Isalnum() | This function identifies the alphanumeric characters | Returns 0 if the passed argument is non – alphanumeric character |
2. | Isalpha() | This function identifies the alphabets from other characters | Returns 0 if the passed argument is not an alphabet |
3. | Isblank() | This function identifies the blank spaces from other characters | Returns 0 if the passed argument is not a blank space |
4. | Iscntrl() | This function identifies the control characters(\n, \b, \t, \r). | Returns 0 if the passed argument is not a control character |
5. | Isdigit() | This function identifies numbers in character. | Returns 0 if the passed argument is not a number |
6. | Islower() | This function identifies the lowercase alphabets. | Returns 0 if the passed argument is not a lowercase alphabet |
7. | Isprint() | This function identifies the printable characters. | Returns 0 if the passed argument is a non-printable character |
8. | Ispunct() | This function identifies punctuation characters (characters that are neither alphanumeric nor space). | Returns 0 if the passed argument is not a punctuation character |
9. | Isspace() | This function identifies white-space characters. | Returns 0 if the passed argument is not a white-space character |
10. | Isupper() | This function identifies the uppercase alphabets. | Returns 0 if the passed argument is not an uppercase alphabet |
11. | Isxdigit() | This function identifies the hexadecimal digit. | Returns 0 if the passed argument is not a hexadecimal digit |
12. | Tolower() | This function converts uppercase alphabet to lowercase alphabet. | Returns lowercase alphabet of the corresponding uppercase alphabet |
13. | Toupper() | This function convert lowercase alphabet to uppercase alphabet. | Returns uppercase alphabet of the corresponding lowercase alphabet |
3. Write a program identifies the number of alphabets, digits:
#include <stdio.h>
// Header file containing character functions #include <ctype.h>
Void identify_alpha_numeric(char a[]) { Int count_alpha = 0, count_digit = 0; For (int i = 0; a[i] != '\0'; i++) { // To check the character is alphabet If (isalpha(a[i])) Count_alpha++;
// To check the character is a digit If (isdigit(a[i])) Count_digit++; } Printf("The number of alphabets are %d\n", Count_alpha); Printf("The number of digits are %d", Count_digit); }
Int main() { // String Initialization Char a[] = "Hi 1234, " " Welcome to GeeksForGeeks"; Identify_alpha_numeric(a); } |
Output:
The number of alphabets are 24
The number of digits are 4
4. Write program identifies the number of uppercase and lowercase alphabets and converts the uppercase to lowercase:
#include <stdio.h>
// Header file containing character functions #include <ctype.h>
Char* identify_convert_ul(char a[]) { Int count_upper = 0, count_lower = 0; For (int i = 0; a[i] != '\0'; i++) {
// To check the uppercase characters If (isupper(a[i])) { Count_upper++; a[i] = tolower(a[i]); }
// To check the lowercase characters Else if (islower(a[i])) { Count_lower++; a[i] = toupper(a[i]); } } Printf("No. Of uppercase characters are %d\n", Count_upper); Printf("No. Of lowercase characters are %d", Count_lower); Return a; }
Int main() { // String Initialization Char a[] = "Hi, Welcome to GeeksForGeeks"; Char* p; p = identify_convert_ul(a); Printf("%s", p); } |
Output:
No. Of uppercase alphabets are 5
No. Of lowercase alphabets are 19
HI, wELCOME TO gEEKSfORgEEKS
5. Write program prints each word in a new line:
#include <stdio.h>
// Header file containing character functions #include <ctype.h>
Char* print_word(char a[]) { For (int i = 0; a[i] != '\0'; i++) {
// Space is replaced // with control character '\n' If (isblank(a[i])) a[i] = '\n'; } Return a; } Int main() { // String Initialization Char a[] = "Hello Everyone." " Welcome to GeeksForGeeks portal. "; Char* p; p = print_word(a); Printf("%s", p); } |
Output:
Hello
Everyone.
Welcome
To
GeeksForGeeks
Portal.
6. Explain Formatted I/O with example
C++ helps you to format the I/O operations like determining the number of digits to be displayed after the decimal point, specifying number base etc.
Example:
- If we want to add + sign as the prefix of out output, we can use the formatting to do so:
- Stream.setf(ios::showpos)
If input=100, output will be +100
- If we want to add trailing zeros in out output to be shown when needed using the formatting:
- Stream.setf(ios::showpoint)
If input=100.0, output will be 100.000
Note: Here, stream is referred to the streams defined in c++ like cin, cout, cerr, clog.
There are two ways to do so:
- Using the ios class or various ios member functions.
- Using manipulators(special functions)
- Formatting using the ios members:
The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags.
Few standard ios class functions are:
- Width(): The width method is used to set the required field width. The output will be displayed in the given width
- Precision(): The precision method is used to set the number of the decimal point to a float value
- Fill(): The fill method is used to set a character to fill in the blank space of a field
- Setf(): The setf method is used to set various flags for formatting output
- Unsetf(): The unsetf method is used To remove the flag setting
7. Write an example of formatted I/O
#include<bits/stdc++.h> Using namespace std;
// The width() function defines width // of the next value to be displayed // in the output at the console. Void IOS_width() { Cout << "--------------------------\n"; Cout << "Implementing ios::width\n\n";
Char c = 'A';
// Adjusting width will be 5. Cout.width(5);
Cout << c <<"\n";
Int temp = 10;
// Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. Cout<<temp; Cout << "\n--------------------------\n"; }
Void IOS_precision() { Cout << "\n--------------------------\n"; Cout << "Implementing ios::precision\n\n"; Cout << "Implementing ios::width"; Cout.setf(ios::fixed, ios::floatfield); Cout.precision(2); Cout<<3.1422; Cout << "\n--------------------------\n"; }
// The fill() function fills the unused // white spaces in a value (to be printed // at the console), with a character of choice. Void IOS_fill() { Cout << "\n--------------------------\n"; Cout << "Implementing ios::fill\n\n"; Char ch = 'a';
// Calling the fill function to fill // the white spaces in a value with a // character our of choice. Cout.fill('*');
Cout.width(10); Cout<<ch <<"\n";
Int i = 1;
// Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. Cout.width(5); Cout<<i; Cout << "\n--------------------------\n"; }
Void IOS_setf() { Cout << "\n--------------------------\n"; Cout << "Implementing ios::setf\n\n"; Int val1=100,val2=200; Cout.setf(ios::showpos); Cout<<val1<<" "<<val2; Cout << "\n--------------------------\n"; }
Void IOS_unsetf() { Cout << "\n--------------------------\n"; Cout << "Implementing ios::unsetf\n\n"; Cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag Cout.unsetf(ios::showpos); Cout<<200.0; Cout << "\n--------------------------\n"; }
// Driver Method Int main() { IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); Return 0; } |
Output:
--------------------------
Implementing ios::width
A
10
--------------------------
--------------------------
Implementing ios::fill
*********a
****1
--------------------------
--------------------------
Implementing ios::setf
+100 +200
--------------------------
--------------------------
Implementing ios::unsetf
200.000
--------------------------
8. Explain Formatting using Manipulators
The second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression.
The standard manipulators are shown below:
- Boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flag
- Dec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flag
- Endl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.
- And: The and manipulator of stream manipulators in C++ is used to Flush the stream
- Ends: The ends manipulator of stream manipulators in C++ is used to Output a null
- Fixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flag
- Flush: The flush manipulator of stream manipulators in C++ is used to Flush a stream
- Hex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flag
- Internal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flag
- Left: The left manipulator of stream manipulators in C++ is used to Turns on the left flag
- Noboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flag
- Noshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flag
- Noshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flag
- Noshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flag
- Noskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flag
- Nounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flag
- Nouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flag
- Oct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flag
- Resetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in f
- Right: The right manipulator of stream manipulators in C++ is used to Turns on the right flag
- Scientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flag
- Setbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to base
- Setfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to ch
- Setiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in f
- Setprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precision
- Setw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to w
- Showbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flag
- Showpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flag
- Showpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flag
- Skipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flag
- Unitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flag
- Uppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flag
- Ws: The ws manipulator of stream manipulators in C++ is used to skip leading white space
9. Write a program To access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program.
Example:
#include <iomanip> #include <iostream> Using namespace std;
Void Example() { // performs ssame as setf( ) Cout << setiosflags(ios::showpos); Cout << 123<<"\n";
// hexadecimal base (i.e., radix 16) Cout << hex << 100 << endl;
// Set the field width Cout << setfill('*') << setw(10) << 2343.0; }
Int main() { Example(); Return 0; } |
Output:
+123
64
*****+2343
The manipulator setiosflags( ) .
10. Explain Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sr.No. | Mode & Description |
1 | r Opens an existing text file for reading purpose. |
2 | w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. |
3 | a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. |
4 | r+ Opens a text file for both reading and writing. |
5 | w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. |
6 | a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. |
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"