© Janice Regan, CMPT 128, Sept 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students C++ Basic Input and output.

Slides:



Advertisements
Similar presentations
CPS120: Introduction to Computer Science INPUT/OUTPUT.
Advertisements

1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
CSC 200 Lecture 2 Matt Kayala 1/25/06. Lecture Objectives More detailed intro to C++ Variables, Expressions, and Assignment Statements Console Input/Output.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
Input and Output in Console Mode UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Input & Output: Console
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Week 1 Algorithmization and Programming Languages.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 1 C++ Basics Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Slide 1. Slide 2 Chapter 1 C++ Basics Slide 3 Learning Objectives  Introduction to C++  Origins, Object-Oriented Programming, Terms  Variables, Expressions,
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
3. FORMATTED INPUT/OUTPUT. The printf Function The first argument in a call of printf is a string, which may contain both ordinary characters and conversion.
CPS120: Introduction to Computer Science Formatted I/O.
Unit 3 Lesson 6 Input and Output Streams with modifications by Mr. Dave Clausen.
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
C Formatted Input/Output
C++ First Steps.
Chapter 1 C++ Basics Copyright © 2016 Pearson, Inc. All rights reserved.
C++ Basic Input and Output (I/O)
Chapter Topics The Basics of a C++ Program Data Types
Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA
Programming Fundamentals
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Basic Elements of C++.
TMF1414 Introduction to Programming
Basic Elements of C++ Chapter 2.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Formatted Input/Output
Formatted Input/Output
INPUT & OUTPUT scanf & printf.
Introduction to C++ Programming
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Introduction to cout / cin
Chapter 4 INPUT AND OUTPUT OBJECTS
Formatted Input/Output
Formatted Input/Output
Introduction to cout / cin
C++ for Engineers and Scientists Second Edition
Presentation transcript:

© Janice Regan, CMPT 128, Sept CMPT 128: Introduction to Computing Science for Engineering Students C++ Basic Input and output

© Janice Regan, CMPT 128, C++ Basic Input and Output (I/O)  To print to your computer’s screen (console) or the read data typed into your keyboard you will need to use objects from the C++ iostream library.  To access the objects in the iostream library you must use a #include pre-processor directive to include their declarations:  #include  This directive tells C++ to use appropriate library so we can use the I/O objects cin, cout, cerr, endl needed for simple input and output

C++ output by example  Consider the code sampleIO.cpp posted with this set of notes.  Lets discuss the examples given in the code © Janice Regan, CMPT 128,

Integers, Doubles and Floats  Each variable or constant in C or C++ must have a type (e. g. int double or float)  Whole numbers with no fractional parts are integers, type int.  Floating point numbers, numbers with fractional points (even when the fractional part is 0) are type float or type double © Janice Regan, CMPT 128,

float vs double  Historically, in both C and C++, type double used more bits to represent each number  More bits allowed variables of type double  To be larger than variables of type float  To be smaller than variables of type float  Be more accurate than variables of type float  The reasons these statements are true will be explained later. © Janice Regan, CMPT 128,

5 C++ Spaces inside “ “ cout << fixed << setprecision(2) << "The balance is $" << balance << endl; cout << “the interest is “ << percent << “ % ” ; cout << precision(5) << percent/100 << endl; PRINTS The balance is $78.50 The interest is % Thee is no space between $ and the final quote in code, there is a space between % and the final “ in the code. Therefore, in the output $ is immediately followed by the value (no space) but % is followed by a space.

C++ endl  Consider the output window (the window in which the output from your program, and the input from your keyboard is displayed.)  When your code executes the instruction cout << endl; The cursor in the output window is moved to the beginning of the next line © Janice Regan, CMPT 128,

7 C++: Moving to a new output line  C++ style: endl  C++ can also use C style: "\n"  escape sequence for the char "newline“ cout << "Hello World" << endl; cout << "Hello World\n";  In C++ both the statements print string "Hello World" to display, then move to next line

© Janice Regan, CMPT 128, C++ Output Window Output  What can you print to your computer’s output window using the insertion operator <<? string name=“John”; const double scale_factor = 2.2; cout << scale_factor // Prints 2.2, the value of constant scale_factor cout << name ; // Prints John, the name stored in variable name cout << “This is a string literal”; // Prints This is a string literal Each cout above prints the value of one variable or constant

© Janice Regan, CMPT 128, C++ Output window Output  You can print the values of more than one variable or constant in a single cout statement cout << “the number of games was ” << numGames << endl << “our team won “ << numWin << “ games” << endl;  Given that the variables have the values  numGames = 23 and numWin = 15  This single cout statement prints the number of games was 23 our team won 15 games to the output window

© Janice Regan, CMPT 128, C++ 3 Equivalent Outputs cout << “the number of games was ” << numGames endl << “ out team won “ << numWin << “ games” << endl; // One cout statement printing many values in succession cout << “the number of games was ” << numGames << endl; cout << “ out team won “ << numWin << “ games” << endl; // Two cout statements, each printing half the values cout << “the number of games was ” ; cout << numGames; cout << endl; cout << “ out team won “ ; cout << numWin ; cout << “ games” ; cout << endl; // each value printed using a single cout statement

Number of digits after decimal  There are two ways in C++ to specify how many digits to print after the decimal point  One method is shown in your text Uses library only Uses “magic formula” to set number of digits after the decimal point  The other method uses manipulators Uses and libraries Syntax is simpler to remember © Janice Regan, CMPT 128,

Explain the “magic formula” cout.setf(ios::fixed); //Tells C++ to display output in fixed format xxx.yyy cout.setf(ios::showpoint); //Tells C++ to always print the decimal point cout.precision(3); //Tells C++ to print 3 digits after the decimal point  Sets your program so all floating point numbers printed after these statements will print in fixed format with 3 digits after the decimal point  Adding another cout.precision(N) statement later in your code will cause all floating point numbers after that statement to print with N digits after the decimal point … © Janice Regan, CMPT 128,

Extend the “magic formula” cout.unsetf(ios::fixed); //Tells C++ to stop displaying in fixed format xxx.yyy cout.setf(ios::scientific); //Tell C++ to start displaying in scientific notation xxx.yyy Ezz  You can switch from fixed point notation to scientific notation (or from scientific notation to fixed point notation)  First you must unset the flag telling C++ to print using floating point. Then you must set the flag to tell C++ to print using scientific notation. (Or unset scientific and set fixed)  Results will not be predictable if you set both flags simultaneously © Janice Regan, CMPT 128,

What else can you specify?  The programmer can explicitly specify how C++ should format the numbers output by their programs using the library  In particular you can specify  The number of digits printed  The number of digits printed after the decimal point  width of field (how many spaces to leave for a value)  Fixed point or scientific notation E2 © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, C++ Manipulators  Used to control how output is formatted  Require user to include library  fixed  scientific  setw()  setprecision()  left  right © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, Manipulators: fixed + setprecision()  fixed, prints number as fixed point, xx.yyy  setprecision(2) indicates 2 digits after the decimal point  Continues to use precision 2 and fixed until told to change in another cout command cout << "$" << fixed << setprecision(2) << 10.3 << " "<< "$" << << endl;  Prints $10.30 $20.51 © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, Manipulators: scientific + setprecision()  scientific and setprecision() manipulators:  setprecision(4) indicates 4 digits after the decimal point cout << “population is " << scientific << setprecision(4) << " is " << << mypop << endl;  If mypop has value cout statement prints: population is e+005 © Janice Regan, CMPT 128, scientific prints number in scientific notation, xxx.yy Ezz

Changing Format: Example cout << fixed << setprecision(2) << "the interest is " << << "% or $”<< dollars << endl; cout << scientific << setprecision(4) << "The amount is " << << endl;  Format changes after scientific is used. The code above print the following when dollars has value 33.12: the interest is 12.34% or $33.12 The amount is e+002 © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, Manipulator: setw()  setw()  Sets the width in characters of the output field  By default output will be right justified in the output field  If the output has the same number of characters as the number or spaces available within the field it will fill the field  If the output has fewer characters as the number or spaces available within the field it will by default be right justified within the field  Note: setw() affects only NEXT value output  Must include setw() manipulator before each item output © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, Manipulator Example: setw()  setw() manipulator: cout << “xxxxxxxxxxxxxxxxxxx”; cout << endl<<"Start" << setw(5) << 10 << setw(4) << 20 << setw(6) << 30;  Prints:  xxxxxxxxxxxxxxxxxxxx Start © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, Manipulator Example: left, right  left and right manipulators: cout << fixed << left << setw(20) << interest << " %" l; cout << endl << setw(20) << balance << endl; cout << setw(20) << right << ;  Prints: xxxxxxxxxxxxxxxxxxxxxx % © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, Input Using cin  Differences:  " >> " (extraction operator) points opposite Think of it as "pointing toward where the data goes"  Object name "cin" used instead of "cout"  No literals allowed for cin Must input "to a variable"  cin >> num;  Waits on-screen for keyboard entry  Value entered at keyboard is "assigned" to num

© Janice Regan, CMPT 128, Prompting for Input:  When using console output and keyboard input always "prompt" user for input cout > numOfDragons;  No "\n" in cout means that the prompt "waits" on same line for keyboard input as follows: Enter number of dragons : Waits here for input

© Janice Regan, CMPT 128, Prompting for Input:  When using console output and keyboard input always "prompt" user for input cout > numOfDragons;  "\n" in cout means that the prompt "waits" on next line for keyboard input as follows: Enter number of dragons : Waits here for input

Variable types and input  Be careful to give the correct type of data when responding to the prompt in a program.  Items from the keyboard will be converted but this may still not give the results you expect © Janice Regan, CMPT 128,

Input the correct type of data  Think of all the information you type in as a continuous stream of characters  If you are reading an integer and you read a decimal point you will stop reading at the decimal point because the decimal point is not a part of an integer  The next time you read you will begin with the decimal point left over from the last input © Janice Regan, CMPT 128,

Incorrect input examples int one; double two; Int three; cout << "enter an integer"; cin >> one; cout << "enter a double "; cin >> two; cout << "enter an integer"; cin >> three; cout << one << “ “ << two << “ " << three; © Janice Regan, CMPT 128, enter an integer4 enter a double 2.4 enter an integer enter an integer5.6 enter a double enter an integer enter an integer12 enter a double 44 enter an integer

Incorrect input examples int one; int two; int three; cout << "enter an integer "; cin >> one; cout << "enter integer 2"; cin >> two; cout<<"enter integer 3"; cin>>three; cout << "XX" << endl << one << " "<< two <<three; © Janice Regan, CMPT 128, enter an integer 4.44 enter integer 2enter integer 3XX enter an integer hello enter integer 2enter integer 3XX

© Janice Regan, CMPT 128, Sept CMPT 128: Introduction to Computing Science for Engineering Students C Basic Input and output Differences from C++

© Janice Regan, CMPT 128, C++ Basic Input and Output (I/O)  To print to your computer’s screen (output window) or the read data typed into your keyboard you will need to use objects from the C stdio library.  To access the objects in the stdio library you must use a #include pre-processor directive to include their declarations:  #include  This directive tells C to use appropriate library so we can use fprintf, fscanf etc

C++ output by example  Consider the code sampleIO.c posted with this set of notes.  Lets discuss the examples given in the code  Each read or print used a C input or output conversion. The input or output conversion used depends on the type of the variable we are trying to print © Janice Regan, CMPT 128,

C input / output conversions © Janice Regan, CMPT 128,

Always check your conversion  A common problem is using a conversion specifier that does no match the type of your variable  This usually causes the value to be printed incorrectly, even if the value itself is correct © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, First example: output /* Print the sum. */ printf(“%f \n", sum);  The %f is the C conversion, all other characters (including blanks, commas, etc.) between the " " will be printed directly to the output line  The %f will be replaced by the value of the variable sum when the program prints the output line

Setting the size of the field  The size of the field is the number of spaces available in which the value can be printed.  The size of the field is specified by an integer between the % and the conversion specifier  %12d /* an integer filling up to 12 characters */  %14lf /* a double filling up to 14 characters */  %17f /* a float filling up to 17 characters */ © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, What is printed? printf ("%6d ", sum); /* sum is an int */  If the value of sum is /*the number is preceded by 3 spaces*/  If the value of sum is -98, /*no preceding blank spaces */  If the value of the sum is -57,639, /*overflows field, no blanks */

Setting the precision  Suppose we have a floating point number and we want it to print with a specified number of digits after the decimal point  The default for C is 6 digits after the decimal point  If we want more or less than 6 digits we must indicate this in our C conversion %12.4f %9.2lf %18.4e © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, What is printed? printf ("%12.2f ", sum); /* sum is a float */  If the value of sum is /*the number is preceded by 6 spaces*/  If the value of sum is /*number is preceded by 3 spaces */  If the value of sum is 4.58 * /*no preceding blank spaces */  If the value of the sum is 2.2* /*overflows field, no blanks */

© Janice Regan, CMPT 128, What is printed? printf ("%12.3 E", sum); /* sum is a float */  If the value of sum is E-006 /* 3 digits after the decimal point, */  If the value of sum is E+005 /* 5 digits for exponent */  If the value of sum is 4.58 * E+009 /* 1 digit for decimal point */  If the value of the sum is 2.2* E+012 /* total 11 digits */

Justification  By default the number is right justified inside the specified field.  You can cause the number to be left justified by adding a – before the integer indicating the size of the field printf ("%12.2fend\n", sum); /* sum is a float */ printf ("%-12.2fend\n", sum); /* sum is a float */  If the value of sum is end © Janice Regan, CMPT 128,

Displaying signs  By default the sign of a number is displayed only when that sign is negative. When the sign is positive no space is reserved for the sign.  You can cause the signs to be shown all the time (both positive and negative) by adding a + before the number indicating the width of the field. © Janice Regan, CMPT 128,

Displaying Signs: Example printf (“%8.3fMMM%8.2fEEE\n", sump, sumn); printf (“%+8.3MMM%+8.2fEEE\n", sump, sumn);  Assume the value of sump is and the value of sumn is MMM EEE MMM EEE © Janice Regan, CMPT 128,

© Janice Regan, CMPT 128, C conversions: Things to remember  ALWAYS use the correct C conversion  When you specify a minimum field width, remember that the sign, the decimal point, and the E (or e) for the exponent all count as digits.  If you specify a minimum field length smaller than the width of the variable being printed, your output will overflow the specified field (continue to the right of the specified field)  Do not specify a precision (.nn) for integers. Integers do not have digits after the decimal

© Janice Regan, CMPT 128, printf(): Things to remember  When there is no space between conversions, there are no spaces between the printed outputs.  Anything you wish to appear in the output that is not the value of a variable must appear in the format statement. This includes spaces  The number of variables in the variable list must match the number of C conversions in the format statement

© Janice Regan, CMPT 128, Special characters in printf statements  There are other strings of characters, called escape sequences, you can place within your format statement to produce particular results  \n newline: move to the next output line  \b backspace: move back one space before printing the next character  \t horizontal tab  \v vertical tab  \\ print a \\? Print a ?  \" print a “\’ print a ‘ % print a %  Note that a format statement should not contain the character produced by typing

First example: C input /* Read the value of temperature. */ scanf(“%f \n", &temperature);  The %f is the C conversion, C will read only characters that can be part of a float variable (we are assuming temperature is a float variable)  The characters typed into the keyboard will replace the value of the variable temperature when the program reads the variable © Janice Regan, CMPT 128,

IMPORTANT  In C ALWAYS use the correction C conversion specifier. If you do not you will probably put the wrong value in your variable  In C always prepend a & to the name of the variable you are reading in the scanf statement © Janice Regan, CMPT 128,

Reading a double  N = scanf(“%12lf”, &myDoubleVariable);  C will read until  It has read 12 characters that could be part of a double variable (digits, decimal point, sign) Leading white space (space, tab, newline) is ignored. It does not count toward the 12 characters.  It encounters a character that could not be part of a double variable (the character that cannot be part of the double variable will be the first character read when the next variable is read) or white space (space, tab, newline … ) © Janice Regan, CMPT 128,

Reading using scanf()  N = scanf(“%12lf %8d”, &myVar1, &my2);  If both myVar1 and my2 are successfully read N will be 2  If myVar1 can be read and my2 cannot be read N will be 1  Suppose the input was  myVar1 would be 12.0  My2 could not be read (first character is. which cannot be part of an integer) © Janice Regan, CMPT 128,