Top Banner
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel 2013 Edit: Ghadah Al hadba
36

CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Dec 13, 2015

Download

Documents

Marshall Hodge
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

CHAPTER 2 PART #3C++ INPUT / OUTPUT

1st Semester 1434 -1435

King Saud University College of Applied studies and Community ServiceCSC1101By: Fatimah Alakeel2013 Edit: Ghadah Al hadba

Page 2: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Outline

Input / Output Operations Using iostream Output Stream Input Stream Common Programming Errors

Page 3: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Input/Output Operations

Input operation an instruction that copies data from an input device

into memory. Input Stream: A stream ( numbers, characters,

strings..etc) that flows from an input device ( i.e.: keyboard, disk drive, network connection) to main memory.

Output operation an instruction that displays information stored in

memory to the output devices (such as the monitor) Output Stream: A stream that flows from main

memory to an output device ( i.e.: screen, printer, disk drive, network connection)

Page 4: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Using iostream

The C++ iostream library provides hundreds of I/O capabilities.

Standard iostream objects:cout - object providing a connection to the

monitorcin - object providing a connection to the

keyboard To perform input and output we send

messages to one of these objects

Page 5: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Output Stream

Page 6: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

The Insertion Operator (<<)

To send output to the screen we use the insertion operator << on the object cout

Format: cout << something;

This something can be:1. Literal e.g cout<<5;

2. Expression e.g cout<<(5+4);

3. Variable or constant e.g cout<<num;

Page 7: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

The Insertion Operator (<<): Literal << is overloaded to output built-in types ( ex. int,

float,…etc) as well as user-defined types (i.e. user defined classes).

The compiler figures out the type of the object and prints it out appropriatelye.g(1): cout << 5; // Outputs 5

e.g(2): cout << 4.1; // Outputs 4.1

e.g(3): cout << “Hello”; // Outputs Hello

e.g(4): cout << ‘\n’; // move the cursor to a newline

String literals should be surrounded with double quotation marks “ “character literals should be surrounded with single quotation marks ‘ ‘

Important: escape sequence characters ( such as : \n, \t)can be either embedded into a string or printed alone as e.g (4)

Page 8: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

The Insertion Operator (<<): Expression

Printing an expression is similar to printing a values since the compiler will calculate then print the resulted value.

Thus, the expression operands should be previously declared and had a valuee.g.(1): cout << (5 + 1); // Outputs 6

e.g.(2): int x = 5 , y;

y = 3;

cout << ((x + y)/ 2); // Outputs 4

Important: With expressions make sure to use parenthesis () , to get the expected result (to be explained in detail Later in lect6)

Page 9: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

The Insertion Operator (<<): Variables and constants

To print the content of a variable of a constant identifier we simply place the identifier name after the insertion operator

cout knows the type of data to output, will be printed probably

e.g.(1): int x = 5;

const double RATE = 3.14;

cout << x; // Outputs 5

cout << RATE; // Outputs 3.14Important: Must not confuse printing text with printing variables , i.e. don’t surround the variable name with a “ “:

int m =12;cout << m; // Outputs 12cout << “m”; // Outputs m

Page 10: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Cascading Stream-Insertion Operators

Allows creating a single output statement that prints 1 or more type of data

e.g. (1)

int age=25;

cout<<“Sarah is “<<age<<“Years Old”;

Output for both

Sarah is 25 Years Old

e.g.int age=25;cout<<“Sarah is “;cout<<age;cout<<“Years Old”;

Compilers start printing from top to downCompilers start printing from left to right

Page 11: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Cascading Stream-Insertion Operators

Allows creating a single output statement that prints 1 or more type of data

e.g. (2)

cout << "How" << " are" << " you?";

How are you?

Output

Page 12: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Formatting Stream Output

Performs formatted and unformatted outputI. Output of numbers in decimal, octal and hexadecimal

using manipulators.

II. Display numbers on different width , filling spaces with characters

III. Varying precision for floating points

IV. Formatted text outputs

Page 13: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

I. Manipulators

C++ manipulators C++ provides various stream manipulators that

perform formatting tasks. Manipulators are functions specifically

designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects.

must include iomanip to use several are provided to do useful things you can also create your own

Page 14: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Output Manipulators (no args)Manipulators included like arguments in extraction

endl - outputs a new line character, flushes outputdec - sets int output to decimalhex - sets int output to hexadecimaloct - sets int output to octal

How to use?Just print the manipulator

you want to convert to ( i.e. dec, hex, or oct) before the intended

integer variable

Page 15: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Output Manipulators (no args)e.g.

#include <iostream>

#include <iomanip>

using namespace std;int main(){int x = 20;cout << x<<“ in hexadecimal is: “<<hex << x << endl; cout << x<<“ in octal is: ”<< oct << x << endl; cout << x<<“ in decimal is: ”<<dec << x << endl;

return 0;}

20 in hexadecimal is: 1420 in octal is: 2420 in decimal is: 20

Output

Page 16: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

II. Setting the Width

You can use the width(int)or setw(int) function to set the minimum width for printing a value.

If the printed value is shorter than the minimum width there will be a padding with a space otherwise it will be printed as it is

This function works ONLY for the next insertion command (more on this later):e.g. (1)

int x = 42;

cout.width(5);

cout << x<<endl;

cout << x;

e.g. (2)

cout << setw (10);

cout << 77 << endl;

4242

Output

77

Output

Page 17: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

II. Setting the Fill Character

Use the fill(char) or setfill(char) function to set the fill character.

The character remains as the fill character until set

again.e.g. (1)

int x = 42;

cout.width(5);

cout.fill(‘*’);

cout << x << ‘\n’;

e.g. (2)

cout << setfill ('x') << setw (10);

cout << 77 << endl;

***42

Output

xxxxxxxx77

Output

Page 18: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

III. Significant Digits in Float

Function precision(int) to set the number of significant digits With fixed:the number of digits to the right of

the decimal point (see e.g. (1)) Without fixed : maximum number of digits to be

displayed in total counting both those before and those after the decimal point. (may convert from fixed to scientific to print) (see e.g. (2))

A call to this function sets the precision for all subsequent output operations until the next precision.

Page 19: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

III. Significant Digits in Float

e.g. (2) [Without fixed]

float y = 23.1415;

cout.precision(1);

cout << y << '\n';

cout.precision(2);

cout << y << '\n';

cout.precision(3);

cout << y << '\n';

e.g. (1) [With fixed]float y = 12.32;cout<<fixed; //Specify that the value is in fixed-point notation cout.precision(1);cout << y << '\n'; cout.precision(2);cout << y << '\n'; cout.precision(3);cout << y << '\n';

12.312.3212.320

Output

2e+012323.1

Output

Page 20: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Using showpoint/noshowpoint showpoint specify that floating-point numbers

(even for whole numbers) should be output with a decimal point, even if they’re zeros. Following the decimal point, as many digits as necessary are written to match the precision.

This setting is reset with stream manipulator noshowpoint.

When the showpoint  manipulator is not set, the decimal point is only written for non-whole numbers.

Page 21: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Using showpoint/noshowpoint

#include <iostream>

#include <iomanip>

using namespace std;

int main () {

double a, b, pi;

a=30.0;

b=10000.0;

pi=3.14165;

cout << a << '\t' << b << '\t' << pi << endl;

cout.precision (5);

cout << showpoint << a << '\t' << b << '\t' << pi << endl;

cout << noshowpoint << a << '\t' << b << '\t' << pi << endl;

return 0;

}

30 10000 3.1416530.000 10000. 3.141630 10000 3.14165

Output

Page 22: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

IV. Formatting Text

To print text you need to include “” around the text Cout <<“This is a Beautiful Day” ; You can add escape sequence for further

options.

Page 23: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Escape Sequence

Page 24: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Examples

cout<<"Please enter the student's grades:”;Please enter the student's grades:

cout<<"The class average is “<< average;The class average is 95.5

cout<<“The total area is “<< area<< “and the total cost is “<< cost << “ S.R.”;The total area is 60.2 and the total cost is 4530 S.R.

Cout<<"The student received an ”<< grade << “ grade in the course.";The student received an A grade in the course.

Average = 95.5

area = 60.2cost = 4530

grade = ‘A’

Page 25: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Examples (Con.)

Cout<<”The grade is << grade << gradesymb;The grade is A+

Cout<<"I am the first line\n”;Cout<<“\n I am the second line\n";I am the first line

I am the second line

grade = ‘A’gradesymb = ‘+’

Page 26: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Input Stream

Page 27: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

The Extraction Operator (>>) To get input from the keyboard we use

the extraction operator >>and the object cin

Format: cin >> Variable; The compiler figures out the type of the

variable and reads in the appropriate typee.g.int X;float Y;cin >> X; // Reads in an integercin >> Y; // Reads in a float

Page 28: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Syntax

cin >> someVariable; cin knows what type of data is to be assigned to someVariable (based on the type of someVariable).

Page 29: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Stream Input

>> (stream-extraction) Used to perform stream input Normally ignores whitespaces (spaces, tabs,

newlines) in the input stream. Returns zero (false) when EOF is encountered,

otherwise returns reference to the object from which it was invoked (i.e. cin) This enables cascaded inputcin >> x >> y;

Page 30: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Stream Input

cin inputs ints, chars, null-terminated strings, string objects but terminates when encounters space

(ASCII character 32) workaround? use the “get” method [ will

see that later]

Page 31: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Chaining Calls

Multiple uses of the insertion and extraction operator can be chained together:cout << E1 << E2 << E3 << … ;

cin >> V1 >> V2 >> V3 >> …; Equivalent to performing the set of

insertion or extraction operators one at a time

Examplecout << “Total sales are $” << sales << ‘\n’;cin >> Sales1 >> Sales2 >> Sales3;

Page 32: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Extraction/Insertion Examplecout << “Hello world! ”;

int i=5;

cout << “The value of i is “ << i << endl;

OUTPUT:

Hello World! The value of i is 5 //endl puts a new line

Char letter;

cout << “Please enter the first letter of your name: “;

cin >> letter;

cout<< “Your name starts with “ << letter;

OUTPUT:

Please enter the first letter of your name: F

Your name starts with F

Page 33: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Common Programming Errors

Page 34: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Common Programming Errors Debugging Process removing errors

from a program

Three (3) kinds of errors :

Syntax Error a violation of the C++ grammar rules,

detected during program translation (compilation).

statement cannot be translated and program cannot be executed

Page 35: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Common Programming Errors cont…

Run-time errorsAn attempt to perform an invalid

operation, detected during program execution.

Occurs when the program directs the computer to perform an illegal operation, such as dividing a number by zero.

The computer will stop executing the program, and displays a diagnostic message indicates the line where the error was detected

Page 36: CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1434 -1435 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.

Common Programming Errors cont…

Logic Error/Design ErrorAn error caused by following an

incorrect algorithmVery difficult to detect - it does not

cause run-time error and does not display message errors.

The only sign of logic error – incorrect program output

Can be detected by testing the program thoroughly, comparing its output to calculated results

To prevent – carefully desk checking the algorithm and written program before you actually type it