introduction to c++ version 1.1. topics c++ structure primitive data types i/o casting strings...
TRANSCRIPT
Introduction to C++
Version 1.1
Topics
C++ StructurePrimitive Data TypesI/OCastingStringsControl Flow
Objective
At the end of this lesson, students shouldbe able to write simple C++ programsusing the standard I/O library, the Stringclass, and primitive data types.
Review: A Simple C# Program
using System;
class Program{ // a constant const int SIZE = 5;
static void Main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }}
Let’s Convert it to C++
using System;
class Program{ // a constant const int SIZE = 5;
static void Main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }}
Let’s Convert it to C++
using System;
class Program{ // a constant const int SIZE = 5;
static void Main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }}
C++ is not a pure object orientedlanguage, so all code does not needto be enclosed inside of a class.
Let’s Convert it to C++
using System;
// a constant const int SIZE = 5;
static void Main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }
Main does not have to be static,in C++ it normally returns an int,and it is all lower case
void main( ) //or void main(void)
return;
Let’s Convert it to C++
using System;
// a constant const int SIZE = 5;
void main(void) //or int main(void) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.WriteLine("The average value is {0}", average); Console.ReadLine(); return; //or return 0; }
The syntax of basic declarations,arithmetic, and control statementsare the same as in C#
Let’s Convert it to C++
using System;
// a constant const int SIZE = 5;
int main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.WriteLine("The average value is {0}", average); Console.ReadLine(); return 0; }
C++ I/O is much different from C#(we’ll discuss the details later)
cout << “The average value is “ << average << endl;
Let’s Convert it to C++
using System;
// a constant const int SIZE = 5;
int main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
Console.ReadLine(); return 0; }
To keep the console window open, we’ll use a system call
cout << “The average value is “ << average << endl;system(“PAUSE”);
Let’s Convert it to C++
using System;
// a constant const int SIZE = 5;
int main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
system(“PAUSE”); return 0; }
Namespaces are declared differentlyin C++. Everything we will use is inthe standard (std) namespace.
cout << “The average value is “ << average << endl;
using namespace std;
Let’s Convert it to C++
using namespace std;
// a constant const int SIZE = 5;
int main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
system(“PAUSE”); return 0; }
Finally, we need to add a new pre-processor directive, that includesheader files that are required forour program to compile correctly.
The iostream header file is required when doing console I/O.
cout << “The average value is “ << average << endl;
#include <iostream>
Here’s the Final C++ Program
using namespace std;
// a constant const int SIZE = 5;
int main( ) {
// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;
system(“PAUSE”); return 0; }
cout << “The average value is “ << average << endl;
#include <iostream>
A Good C++ Code Skeleton
using namespace std;
// declare global constants here#include “skel.h” void main(void) {
// declare local variable variables here // C++ statements
system(“PAUSE”); }
#include <iostream>
.h file
.cpp file
Primitive Data Types
C++ has fewer primitive data types than does C#,but the primary ones that we will use are exactlythe same … int, double, bool, and char and unsigned.
There is a major difference between C++ data typesand C# data types. In C++, the size of a data typeis determined by the underlying hardware, it is notdefined by the language.
Assignment and Arithmetic workjust as they do in C#.
C++ Input and Output
In place of C#s Console class, we need twoC++ Objects to do console input and output
cincin is an object of the istream class. To use cin, you must #include iostream in your program.
This object represents the standard input stream. The cin object is created automatically for you.
keyboard buffercin program
keyboard buffer
cout is an object of the ostream class. This objectrepresents the standard output stream. It
is also created automatically for you.
output buffercout program
cout
display buffer
The Stream Insertion Operator, <<
a binary operator (it takes two operands)the left hand operand must be an output streamthe right hand operand
– is converted into text– the text data is then copied into the stream
display buffer
int a = 5; a 0000 0000 0000 0101
the integer 5
0000 0000 0011 0101
the character 5
cout
cout << a;
5
multiple pieces of data are output bycascading the << operator …
cout << “The answer is “ << a;
If you want data to appear on a new line, you mustexplicitly add the newline character to the outputstream. There is no WriteLine operation.
Special characters are added to the streamusing the escape character \
\t\netc …
cout << “The answer is “ << a << ‘\n’;
the endl stream manipulator can be added to the outputstream. It does two things:
It adds a new line to the stream.
It forces the buffer to be output
cout << “Hello” << endl;
Formatting Numbers
Output formatting in C++ is quite different fromC#’s output formatting.
To display a double or a float in standard decimal notation
cout.setf(ios::fixed);
setf( ) is a function in the cout object. It is responsible forsetting formatting flags. We will study these in much moredetail in a later section. In this case, we are setting theios::fixed flag. This makes the output appear as a normaldecimal number instead of in scientific notation.
cout.setf(ios::showpoint);
the ios::showpoint flag guarantees that a decimal pointwill be displayed in the output.
cout.precision(2);
the cout.precision( ) function determines how many digitswill be displayed after the decimal point.
The default formatting, is the“general” format. In this caseprecision defines the number ofdigits in total to be displayed
Example
double price = 78.5;cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precison(2);cout << “The price is $” << price << endl;
The stream extraction operator, >>
Also a binary operatorThe left operand must be an input streamAny initial white space is skipped, then the stream is read up
to the next white space character ( tab, space, new-line )If necessary, the text just read is converted to match the
type of the right operand. An error occurs if the conversion cannot be done.
The data is stored in the right operand
keyboard buffercin
int a;cin >> a;
a
0000 0000 0011 0101
the character 5
0000 0000 0000 0101
5 72 hello
reading stops when white space is encountered
In C#, we always read a string from theConsole, and then used a Parse method toconvert the string to the desired data type.
In C++, this conversion happens via the >> operator.
However, no exception occurs if the conversioncannot be done.
Failed Input
Consider the following:
A program contains the statements int number = 0; cin >> number
What happens if the user types the letter “t”?
The stream extraction operator is not able toconvert the letter “t” into a proper integer value.Three important things happen, without warning:
1. No input occurs, so the variable number contains whatever value it had previously.
2. The letter “t” remains in the input buffer, so a subsequent read operation will try to read it by error.
3. The object cin sets itself to a “failed” state, and subsequent input operations will all fail.
Handling Failed Input
As noted, if input fails, no data is input.
We can detect when this happens by testing the state ofthe input stream object.
if (cin.fail( ) ) { cout << “Invalid input occured”; . . . }
There is a well known idiom in C++ that makeshandling failed input much easier. The expression
cin >> number;
has a value, which is the value of the object cin itself.if the value of cin is “good”, we can go ahead and process the data. The statement to do this looks like
if (cin >> number) { // process the input
}
Recall that once the stream object fails, all subsequentread operations will fail. How do we fix that?
The stream objects have a member function namedclear( ), that resets the failed state back to good.
cin.clear( );
Using the Stream State to Control a Loop
cout << “\nEnter an integer value (or ‘q’ to quit): “;while (cin >> number){ // process the data
}cin.clear( ); // clear the fail statestring dummyValue; // get the ‘q’ out of the buffercin >> dummyValue;. . .
This code will process user input until a non-integer value is typed:
you can also cascade the stream extraction operator:
cin >> a >> b;
You can control the size of an input field withthe setw( n ) stream manipulator.
cin >> setw(5) >> title;
But … keep in mind that this can leave data in the buffer.
cin.get
The get function of the istream class works similarto the stream extraction operator. With no parameter,it gets one character from the input stream.
cin.get( );
cin.ignore( )
This function reads in a character and ignoresit. The character read in is discarded.
cin.ignore( );
cin.ignore( )
This version of the function reads in n charactersand ignores them.
cin.ignore(n);
This version of the function reads in n charactersor until it encounters the delimiter character,and ignores the characters read.
cin.ignore(n, ‘\n’);
In C++, you can use the same style of castas you did in C#, but the preferred way tocast in C++ is to write, for example
Casting
int number = static_cast<int> myDoubleValue;
just use
int number = (int)myDoubleValue;
Strings
C++ has a string class similar to C#’s string class, but notquite as powerful.
Declaring a String(you must #include <string>)
string myName;
string myName = Prof. Fairclough”;
Reading a line into a string
This function is similar to cin.get( )except thatit reads an entire line of data, including spaces,and the data is stored in a string object. This isthe preferred way of reading in a line of data.It is equivalent to C#’s ReadLine method.
getline(cin, stringName);
cin.ignore( ) … again
Why is ignore useful? Try the following code…
int numItems;string description;
cout << “\nenter the number of items and description: “;cin >> numItems;getline(cin, description);
When prompted, enter the data on two lines.
C++ Control Flow
With a few minor exceptions, the statements that controlflow through a C++ program look and work the same as they do in C#
Switch
In C#, each case must contain a break statement. Itis legal to drop through from one case to the next. Youcan switch on intergal and char types only. NOT strings! DARN!
switch (num){ case 1: a = a + 5; b = b + 3; case 2: a = a + 6; b = b + 4; case 3: a = a – 7; b = b – 1;}
if num = 3, only this code executes
if num = 2, then this code executes
if num =1, thenthis code executes
This is valid code in C++
There is no foreach statement in C++