Download presentation
Presentation is loading. Please wait.
Published byBernard Moore Modified over 9 years ago
1
© Janice Regan, CMPT 128, Sept 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students C++ Basic Input and output
2
© Janice Regan, CMPT 128, 2007-2013 1 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
3
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, 2007-2013 2
4
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, 2007-2013 3
5
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, 2007-2013 4
6
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 12.45 % 0.12450 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.
7
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, 2007-2013 6
8
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
9
© Janice Regan, CMPT 128, 2007-2013 8 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
10
© Janice Regan, CMPT 128, 2007-2013 9 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
11
© Janice Regan, CMPT 128, 2007-2013 10 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
12
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, 2007-2013 11
13
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, 2007-2013 12
14
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, 2007-2013 13
15
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 123.4 or scientific notation 1.234 E2 © Janice Regan, CMPT 128, 2007-2013 14
16
© Janice Regan, CMPT 128, 2007-2013 15 C++ Manipulators Used to control how output is formatted Require user to include library fixed scientific setw() setprecision() left right © Janice Regan, CMPT 128, 2007-2012
17
© Janice Regan, CMPT 128, 2007-2013 16 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 << " "<< "$" << 20.512 << endl; Prints $10.30 $20.51 © Janice Regan, CMPT 128, 2007-2012
18
© Janice Regan, CMPT 128, 2007-2013 17 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 333444 cout statement prints: population is 3.3345 e+005 © Janice Regan, CMPT 128, 2007-2012 scientific prints number in scientific notation, xxx.yy Ezz
19
Changing Format: Example cout << fixed << setprecision(2) << "the interest is " << 12.33333 << "% or $”<< dollars << endl; cout << scientific << setprecision(4) << "The amount is " << 111.234567 << 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 1.1123e+002 © Janice Regan, CMPT 128, 2007-2013 18
20
© Janice Regan, CMPT 128, 2007-2013 19 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, 2007-2012
21
© Janice Regan, CMPT 128, 2007-2013 20 Manipulator Example: setw() setw() manipulator: cout << “xxxxxxxxxxxxxxxxxxx”; cout << endl<<"Start" << setw(5) << 10 << setw(4) << 20 << setw(6) << 30; Prints: xxxxxxxxxxxxxxxxxxxx Start 10 20 30 © Janice Regan, CMPT 128, 2007-2012
22
© Janice Regan, CMPT 128, 2007-2013 21 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 << 2333345.45678 ; Prints: xxxxxxxxxxxxxxxxxxxxxx 2.300000 % 23.456000 2333345.456780 © Janice Regan, CMPT 128, 2007-2012
23
© Janice Regan, CMPT 128, 2007-2013 22 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
24
© Janice Regan, CMPT 128, 2007-2013 23 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
25
© Janice Regan, CMPT 128, 2007-2013 24 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
26
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, 2007-2013 25
27
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, 2007-2013 26
28
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, 2007-2013 27 enter an integer4 enter a double 2.4 enter an integer7 4 2.4 7 enter an integer5.6 enter a double enter an integer6 5 0.6 6 enter an integer12 enter a double 44 enter an integer88 12 44 88
29
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, 2007-2013 28 enter an integer 4.44 enter integer 2enter integer 3XX 4 -858993460-858993460 enter an integer hello enter integer 2enter integer 3XX -858993460 -858993460-858993460
30
© Janice Regan, CMPT 128, Sept 2007 29 CMPT 128: Introduction to Computing Science for Engineering Students C Basic Input and output Differences from C++
31
© Janice Regan, CMPT 128, 2007-2013 30 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
32
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, 2007-2013 31
33
C input / output conversions © Janice Regan, CMPT 128, 2007-2013 32
34
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, 2007-2013 33
35
© Janice Regan, CMPT 128, 2007-2013 34 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
36
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 */ 12345678901234567890 456738510 375.340587 © Janice Regan, CMPT 128, 2007-2013 35
37
© Janice Regan, CMPT 128, 2007-2013 36 What is printed? printf ("%6d ", sum); /* sum is an int */ If the value of sum is 589 589 /*the number is preceded by 3 spaces*/ If the value of sum is -98,765 -98765 /*no preceding blank spaces */ If the value of the sum is -57,639,862 -57639862 /*overflows field, no blanks */
38
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, 2007-2013 37
39
© Janice Regan, CMPT 128, 2007-2013 38 What is printed? printf ("%12.2f ", sum); /* sum is a float */ If the value of sum is 589.73 589.73 /*the number is preceded by 6 spaces*/ If the value of sum is 798765.987632 798765.99 /*number is preceded by 3 spaces */ If the value of sum is 4.58 *10 9 458000000.00 /*no preceding blank spaces */ If the value of the sum is 2.2*10 12 220000000000.00 /*overflows field, no blanks */
40
© Janice Regan, CMPT 128, 2007-2013 39 What is printed? printf ("%12.3 E", sum); /* sum is a float */ If the value of sum is 0.0000058973 5.897E-006 /* 3 digits after the decimal point, */ If the value of sum is 798765.987632 7.988E+005 /* 5 digits for exponent */ If the value of sum is 4.58 *10 9 4.580E+009 /* 1 digit for decimal point */ If the value of the sum is 2.2*10 12 2.200E+012 /* total 11 digits */
41
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 589.73 589.73end © Janice Regan, CMPT 128, 2007-2013 40
42
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, 2007-2013 41
43
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 589.73 and the value of sumn is -475.7 589.730MMM -475.70EEE +589.730MMM-475.70 EEE © Janice Regan, CMPT 128, 2007-2013 42
44
© Janice Regan, CMPT 128, 2007-2013 43 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
45
© Janice Regan, CMPT 128, 2007-2013 44 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
46
© Janice Regan, CMPT 128, 2007-2013 45 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
47
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, 2007-2013 46
48
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, 2007-2013 47
49
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, 2007-2013 48
50
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 12..72 myVar1 would be 12.0 My2 could not be read (first character is. which cannot be part of an integer) © Janice Regan, CMPT 128, 2007-2013 49
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.