0% found this document useful (0 votes)
23 views41 pages

C++ - Week5

This document covers basic input/output operations in C++ using cout and cin operators, as well as printf() and scanf() functions from C. It explains how to print data to the screen, receive user input, and format output using manipulators like setw and setprecision. Additionally, it provides examples of using these functions to handle various data types and formats.

Uploaded by

Yasir Idris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views41 pages

C++ - Week5

This document covers basic input/output operations in C++ using cout and cin operators, as well as printf() and scanf() functions from C. It explains how to print data to the screen, receive user input, and format output using manipulators like setw and setprecision. Additionally, it provides examples of using these functions to handle various data types and formats.

Uploaded by

Yasir Idris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Week 5 – Simple input/output

Course Lecturer:
Muhammad Shamsu Usman
(muhdshamsususmangmail.com)

Department of Computer Science, FUD -


2024/2025
Simple Input/Output
 You have already seen the cout operator. It
prints values to the screen.
 There is much more to cout than you have
learned. Using cout and the screen (the most
common output device), you can print
information any way you want it.
 Your programs also become much more
powerful if you learn to receive input from the
keyboard.
 Cin is an operator that mirrors the cout. Instead
of sending output values to the screen, cin
accepts values that the user types at the
 The cout and cin operators offer the new C++
programmer input and output operators they can
use with relative ease.
 Both of these operators have a limited scope,
but they give you the ability to send output from
and receive input to your programs.

 There are corresponding functions supplied with


all C++ compilers called printf() and scanf().
 These functions are still used by C++
programmers due to their widespread use in
regular C programs.
 This section revisits

 The cout operator


 Control operators
 The cin operator
 The printf() output function
 The scanf() input function
The cout Operator
 The cout operator sends data to the standard
output device.
 The standard output device is usually the
screen

 At this point, cout sends all output to the screen.


 The format of the
cout << data [ << data ];

 The data placeholder can be variables, literals,


expressions, or a combination of all three.
Printing Strings
 To print a string constant, simply type the
string constant after the cout operator.

 For example, to print the string, The rain in


Spain, you would simply type this:

 Print the sentence “The rain in Spain” to the


screen.

cout << “The rain in Dutse”;


 You must remember, however, that cout does
not perform an automatic carriage return.

 This means the screen’s cursor appears directly


after the last printed character and subsequent
couts begin thereafter.
Examples
1. The following program stores a few values in three variables, then prints the
results:
#include <iostream.h>
main()
{
char first = ‘E’; // Store some character, integer,
char middle = ‘W’; // and floating-point variable.
char last = ‘C’;
int age = 32;
int dependents = 2;
float salary = 25000.00;
float bonus = 575.25;
// Prints the results.
cout << first << middle << last;
cout << age << dependents;
cout << salary << bonus;
return 0;
}
2. If you have to print a table of numbers, you can use the \t tab
character to do so. Place the tab character between each of
the printed numbers. The following program prints a list of
team names and number of hits for the first three weeks of
the season:

// Prints a table of team names and hits for three weeks.


#include <iostream.h>
main()
{
cout << “Parrots\tRams\tKings\tTitans\tChargers\n”;
cout << “3\t5\t3\t1\t0\n”;
cout << “2\t5\t1\t0\t1\n”;
cout << “2\t6\t4\t3\t0\n”;
return 0;
}
Control Operators
 You have already seen the need for additional
program-output control.
 All floating-point numbers print with too many
decimal places for most applications.
 What if you want to print only dollars and cents (two
decimal places), or print an average with a single
decimal place?
 You can specify how many print positions to use in
printing a number.
 For example, the following cout prints the number
456, using three positions (the length of the data):
cout << 456;
 If the 456 were stored in an integer variable, it
would still use three positions to print because the
number of digits printed is three.
 However, you can specify how many positions to
print. The following cout prints the number 456 in
five positions (with two leading spaces):
cout << setw(5) << setfill(‘ ‘) << 456;

 You typically use the setw manipulator when you


want to print data in uniform columns.
 Be sure to include the iomanip.h header file in any
programs that use manipulators because iomanip.h
describes how the setw works to the compiler.
 The following program shows you the importance of the width
number. Each cout output is described in the comment to its left.

// Illustrates various integer width cout modifiers.


#include <iostream.h>
#include <iomanip.h>
main()
{ // The output appears below.
cout << 456 << 456 << 456 << “\n”; // Prints 456456456
cout << setw(5) << 456 << setw(5) << 456 << setw(5) <<
456 << “\n”; // Prints 456 456 456
cout << setw(7) << 456 << setw(7) << 456 << setw(7) <<
456 << “ \n”; // Prints 456 456 456
return 0;
}
 If you want to control the width of your data, use a setw manipulator. Instead of using the
tab character, \t, which is limited to eight spaces, this program uses the width specifier to
set the tabs. It ensures that each column is 10 characters wide.
 // Prints a table of team names and hits for three weeks
 // using width-modifying conversion characters.
 #include <iostream.h>
 #include <iomanip.h>
 main()
 {
 cout << setw(10) << “Parrots” << setw(10) << “Rams” << setw(10) << “Kings” << setw(10)
<< “Titans” << setw(10) << “Chargers” << “\n”;
 cout << setw(10) << 3 << setw(10) << 5 << setw(10) << 2 << setw(10) << 1 << setw(10)
<< 0 << “\n”;
 cout << setw(10) << 2 << setw(10) << 5 << setw(10) << 1 << setw(10) << 0 << setw(10)
<< 1 << “\n”;
 cout << setw(10) << 2 << setw(10) << 6 << setw(10) << 4 << setw(10) << 3 << setw(10)
<< 0 << “\n”;
 return 0;
 }
The following program is a payroll program. The output is in
“dollars and cents” because the dollar amounts print
properly to two decimal places.
// Computes and prints payroll data properly in dollars
// and cents.
#include <iostream.h>
#include <iomanip.h>
main()
{
char emp_name[ ] = “Larry Payton”;
char pay_date[ ] = “03/09/92”;
int hours_worked = 43;
float rate = 7.75; // Pay per hour
float tax_rate = .32; // Tax percentage rate
float gross_pay, taxes, net_pay;
// Computes the pay amount.
gross_pay = hours_worked * rate;
taxes = tax_rate * gross_pay;
net_pay = gross_pay - taxes;
// Prints the results.
cout << “As of: “ << pay_date << “\n”;
cout << emp_name << “ worked “ << hours_worked <<“ hours\n”;
cout << “and got paid “ << setw(2) << setprecision(2) << gross_pay << “\n”;
cout << “After taxes of: “ << setw(6) << setprecision(2) << taxes << “\n”;
cout << “his take-home pay was $” << setw(8) << setprecision(2) << net_pay
<< “\n”;
return 0;
}
The cin Operator
 You now understand how C++ represents data and
variables, and you know how to print the data.

 However, this is not always the best way to transfer


data to your programs; you rarely know what your
data is when you write your programs.
 The data is known only when you run the
programs (or another user runs them).

 The cin operator is one way to input from the


keyboard.

 When your programs reach the line with a cin,


the user can enter values directly into variables.

 Your program can then process those variables


and produce output.
 The cin operator looks much like cout. It
contains one or more variables that appear to
the right of the operator name.

 The format of the cin is


cin >> value [>> values];

 The iostream.h header file contains the


information C++ needs to use cin, so include it
when using cin.

Examples
If you wanted a program that computed a seven percent sales tax, you
could use the cin statement to figure the sales, compute the tax, and
print the results as the following program shows:
// Prompt for a sales amount and print the sales tax.
#include <iostream.h>
#include <iomanip.h>
main()
{
float total_sale; // User’s sale amount goes here.
float stax;
// Display a message for the user.
cout << “What is the total amount of the sale? “;
// Receive the sales amount from user.
cin >> total_sale;
// Calculate sales tax.
stax = total_sale * .07;
cout << “The sales tax for “ << setprecision(2) << total_sale <<
“ is “ << setprecision (2) << stax;
return 0;
}

 Because the first cout does not contain a newline character,


\n, the user’s response to the prompt appears to the right of
the question mark.
printf() and scanf()
 Before C++, C programmers had to rely on
function calls to perform input and output.

 Two of those functions, printf() and scanf(), are


still used frequently in C++ programs, although
cout and cin have advantages over them.

 printf() (like cout) prints values to the screen and


scanf() (like cin) inputs values from the keyboard.
 printf() requires a controlling format string that
describes the data you want to print.

 Likewise, scanf() requires a controlling format


string that describes the data the program wants
to receive from the keyboard.
The printf() Function
 printf() sends data to the standard output device,
which is generally the screen.

 The format of printf() is different from those of


 regular C++ commands. The values that go
inside the parentheses vary, depending on the
data you are printing.
 However, as a general rule, the following printf()
format holds true:

printf(control_string [, one or more values]);


 Notice printf() always requires a control_string.
This is a string, or a character array containing a
string, that determines how the rest of the values
(if any are listed) print.

 These values can be variables, literals,


expressions, or a combination of all three.

 The easiest data to print with printf() are strings.

 To print a string constant, you simply type that


string constant inside the printf() function.
 For example, to print the string The rain in pain,
 you would simply type the following:

printf(“The rain in Spain”);

 printf(), like cout, does not perform an automatic


carriage return. Subsequent printf() begin next
to that last printed character.

 If you want a carriage return, you must supply a


newline character, as so:
printf(“The rain in Spain\n”);
 You can print strings stored in character arrays
also by typing the array name inside the printf().
 For example, if you were to store your name in
an array defined as:
char my_name[] = “Hamisu Isah”;
 you could print the name with this printf():
printf(my_name);
 You must include the stdio.h header file when
using printf() and scanf() because stdio.h
determines how the input and output functions
work in the compiler.
 The following program assigns a message in a
character array, then prints that message.
 // Prints a string stored in a character array.
 #include <stdio.h>
 main()
 {
 char message[] = “Please turn on your printer”;
 printf(message);
 return 0;
 }
Conversion Characters
 Inside most printf() control strings are
conversion characters.
 These special characters tell printf() exactly
how the data (following the characters) are to
be interpreted.
Conversion Character Output
%s String of characters (until null zero is reached)
%c Character
%d Decimal Integer
%f Floating Point Numbers
%u Unsigned Integer
%x Hexadecimal Number
%% Print a percentage sign (%)
 Because any type of data can go inside the
printf()’s parentheses, these conversion
characters are required any time you print more
than a single string constant.

 If you don’t want to print a string, the string


constant must contain at least one of the
conversion characters.

 When you want to print a numeric constant or


variable, you must include the proper
conversion character inside the printf() control
string.
 If i, j, and k are integer variables, you cannot
print them with the printf() that follows.

printf(i,j,k);

 Because printf() is a function and not a


command, this printf() function has no way of
knowing what type the variables are.

 The results are unpredictable, and you might


see garbage on your screen—if anything
appears at all.
 When you print numbers, you must first print a
control string that includes the format of those
numbers. The following printf() prints a string.

 In the output from this line, a string appears with


an integer (%d) and a floating-point number (%f)
printed inside that string.

printf(“I am Abdullahi, I am %d years old, and I make %f\n”, 35,


34050.25);

 This produces the following output:

I am Abdullahi, I am 35 years old, and I make 34050.25


Examples
// Prints values in variables with appropriate labels.
#include <stdio.h>
main()
{
char first=’E’; // Store some character, integer,
char middle=’W’; // and floating-point variable.
char last=’C’;
int age=32;
int dependents=2;
float salary=25000.00;
float bonus=575.25;
/* Prints the results. */
printf(“Here are the initials\n”);
printf(“%c%c%c\n\n”, first, middle, last);
printf(“The age and number of dependents are\n”);
printf(“%d %d\n\n”, age, dependents);
printf(“The salary and bonus are\n”);
printf(“%f %f”, salary, bonus);
return 0;
}
The scanf() Function
 The scanf() function reads input from the
keyboard.
 When your programs reach the line with a
scanf(), the user can enter values directly into
variables.
 Your program can then process the variables
and produce output.

 The scanf() function looks much like printf(). It


contains a control string and one or more
variables to the right of the control string.
 The control string informs C++ exactly what the
incoming keyboard values look like, and what
their types are.

 The format of scanf() is


scanf(control_string, one or more values);

 The scanf() control_string uses almost the same


conversion characters as the printf()
control_string, with two slight differences.

 You should never include the newline character,


\n, in a scanf() control string.
 The scanf() function “knows” when the input is
finished when the user presses Enter.

 If you supply an additional newline code, scanf()


might not terminate properly. Also, always put a
beginning space inside every scanf() control
string.

 This does not affect the user’s input, but scanf()


sometimes requires it to work properly.
 scanf() poses a few problems. The scanf()
function requires that user type the input exactly
the way control_string specifies.
 Because you cannot control your user’s typing,
this cannot always be ensured.

 For example, you might want the user to enter


an integer value followed by a floating-point
value, but your user might decide to enter
something else! If this happens, there is not
much you can do.

 The resulting input is incorrect, but your C


program has no reliable method for testing user
accuracy before your program is run.
 Another problem with scanf() is not as easy for
beginners to understand as the last.

 The scanf() function requires that you use


pointer variables, not regular variables, in its
parentheses.

 Although this sounds complicated, it doesn’t


have to be.

 You should have no problem with scanf()’s


pointer requirements if you remember these two
simple rules:
 1. Always put an ampersand (&) before
variable names inside a scanf().
 2. Never put an ampersand (&) before an array
name inside a scanf().
 Despite these strange scanf() rules, you can
learn this function quickly by looking at a few
examples.
 Examples
 1. If you want a program that computes a seven
percent sales tax, you could use the scanf()
statement to receive the sales, compute the tax,
and print the results as the following program
shows.
// Compute a sales amount and print the sales tax.
#include <stdio.h>
main()
{
float total_sale; // User’s sale amount goes here.
float stax;
// Display a message for the user.
printf(“What is the total amount of the sale? “);
// Compute the sales amount from user.
scanf(“ %f”, &total_sale); // Don’t forget the beginning
// space and an &.
stax = total_sale * .07; // Calculate the sales tax.
printf(“The sales tax for %.2f is %.2f”, total_sale, stax);
return 0;
}
 Read more about simple
input/output

You might also like