C++ programming intro

22
Copyright © 2004 Dept. of Computer Science and Engineering, Washington University CS 342: Intro to C++ Programming A Simple C++ Program #include <iostream> using namespace std; int main() { cout << “hello, world!” << endl; return 0; }

Transcript of C++ programming intro

Page 1: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

A Simple C++ Program

#include <iostream>using namespace std;

int main() {cout << “hello, world!” << endl;return 0;

}

Page 2: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

#include <iostream>• #include tells the precompiler to include a file• Usually, we include header files

– Contain declarations of structs, classes, functions

• Sometimes we include template definitions– Varies from compiler to compiler– Advanced topic we’ll cover later in the semester

• <iostream> is the C++ label for a standard header file for input and output streams

Page 3: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

using namespace std;• The using directive tells the compiler to include code

from libraries in a separate namespace– Similar idea to Ada/Pascal “packages”

• C++ provides such a namespace for its standard library– cout, cin, cerr standard iostreams and much more

• Namespaces reduce collisions between symbols– If another library defined cout we could say std::cout

• Can also apply using more selectively:– E.g., just using std::cout

Page 4: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

int main()• Declares the main function of any C++ program• Here, takes no parameters and returns an integer

– By convention in UNIX and many other platforms• returning 0 means success• returning non-zero indicates failure (may return error codes)

• Who calls main?– The runtime environment (often from a function called crt0)

• What about the stuff in braces?– It’s the body of function main, its definition

Page 5: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

cout<<“hello, world!”<<endl;• Uses the standard output iostream, named cout

– For standard input, use cin– For standard error, use cerr

• << is an operator for inserting into the stream– A member “function” of the ostream class– Returns a reference to stream on which its called– Can be applied repeatedly to references left-to-right

• “hello, world!” is a C-style string– A 14-postion character array terminated by ‘\0’

• endl is an iostream manipulator– Ends the line, by inserting end-of-line character(s)– Also flushes the stream

Page 6: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

A Slightly Bigger C++ Program#include <iostream>using namespace std;int main(int argc, char * argv[]) {for (int i = 0; i < argc; ++i) {

cout << argv[i] << endl;}return 0;

}

Page 7: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

int argc, char * argv[]• A way to affect the program’s behavior

– Carry parameters with which program was called– Passed as parameters to main from crt0– Passed by value (we’ll discuss what that means)

• argc– An integer with the number of parameters (>=1)

• argv– An array of pointers to C-style character strings– Its array-length is the value stored in argc– The name of the program is kept in argv[0]

Page 8: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

for(int i = 0; i < argc; ++i)• Standard C++ for loop syntax

– Initialization statement done once at start of loop– Test expression done before running each time– Expression to increment after running each time

• int i = 0– Declares integer i (scope is the loop itself)– Initializes i to hold value 0

• i < argc– Tests whether or not we’re still inside the array!– Reading/writing memory we don’t own can crash the

program (if we’re really lucky!)• ++i

– increments the array position

Page 9: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

{cout << argv[i] << endl;}• Body of the for loop• You should use braces, even if there’s only

one line of code– Avoids maintenance errors when

adding/modifying code– Ensures semantics & indentation say same thing

• argv[i]– An example of array indexing– Specifies ith position from start of argv

Page 10: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Types• int, long, short, char (integer division)• float, double (floating point division)• signed (default) and unsigned types• bool type• enumerations

– enum primary_colors {red, blue, yellow};• structs and classes• pointers and references• mutable (default) vs. const types

Page 11: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Loops and Conditionals• Loops

– for– while– do

• Conditionals– if, else, else if– ?: operator– switch

Page 12: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Operators• Relational operators

== <= >= < > !=

• Assignment operators= *= /= %= += -= &= |=

• Logical operators! && ||

• Member selection operators-> .

All of these return values– Be careful of == and =

Page 13: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Functions• In C++, behavior need not be part of a class

– We’ll distinguish “plain old” functions vs. member functions

• Pass parameters by reference vs. by value• Put declaration prototypes (no body) in header files• Put definitions in source files (compilation units)• Libraries often offer lots of helpful functions

– E.g., isalpha () from the <cctype> library

Page 14: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

Parameter/Variable Declarations• Read a function parameter or local variable

declaration right to leftint i; “i is an integer”int & r; “r is a reference to an integer”int * p; “p is a pointer to an integer”int * & q; “q is a reference to a pointer to an integer”int * const c; “c is a const pointer to an integer”int const * d; “d is a pointer to a const integer”

• Read a function pointer declaration inside out– More on this later

Page 15: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

Pass By Referencevoid foo() {

int i = 7;baz (i);

}

void baz(int & j) {j = 3;

}

7 ? 3

local variable i

j is a reference to thevariable passed to baz

7 ? 3

Page 16: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

Pass By Valuevoid foo() {

int i = 7;baz (i);

}

void baz(int j) {j = 3;

}

7

7 ? 3

local variable i

local variable j (initialized with the value passed to baz)

Page 17: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Classes and Structsstruct MyData {MyData(int i) :m_x(i){}int m_x;

};

class MyObject {public:MyObject(int y);~MyObject();

private:int m_y;

};

• Struct members are public by default

• Class members are private by default

• Both can have – Constructors– Destructors– Member variables– Member functions

• Common practice:– use structs for data– use classes for objects with

methods• Declarations usually go in

header files

Page 18: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Classes and StructsWe also need an implementation

– Generally in the .cpp file

MyObject::MyObject(int y) :m_y(y) {// It’s a good idea to assert your argumentsassert(y > 0);

}

MyObject::~MyObject() {}

Page 19: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ string Class#include <iostream>#include <string>using namespace std;int main() {string s; // emptys = “”; // emptys = “hello”; s += “, ”;s = s + “world!”;cout << s << endl;return 0;

}

• <string> header file• Various constructors

– Prata, pp. 780• Assignment operator• Overloaded operators

+= + < >= == []• The last one is really

useful: indexes stringif (s[0] == ‘h’) …

Page 20: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ Input/Output Stream Classes#include <iostream>using namespace std;int main() {int i;// cout == std ostreamcout << “how many?”

<< endl;// cin == std istreamcin >> i; cout << “You said ” << i

<< ‘.’ << endl;return 0;

}

• <iostream> header file– Use istream for input– Use ostream for output

• Overloaded operators<< ostream insertion operator>> istream extraction operator

• Other methods– ostream: write, put– istream: get, eof, good, clear

• Stream manipulators– ostream: flush, endl, setwidth,

setprecision, hex, boolalpha– Prata pp. 891-892

Page 21: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ File I/O Stream Classes#include <fstream>using namespace std;int main() {ifstream ifs;ifs.open(“in.txt”);ofstream ofs(“out.txt”);if (ifs.is_open() &&

ofs.is_open()) {int i;ifs >> i;ofs << i;

}ifs.close(); ofs.close();return 0;

}

• <fstream> header file– Use ifstream for input– Use ofstream for output

• Other methods– open, is_open, close– getline– seekg, seekp

• File modes– in, out, ate, app, trunc, binary

Page 22: C++ programming intro

Copyright © 2004 Dept. of Computer Science and Engineering, Washington University

CS 342: Intro to C++ Programming

C++ String Stream Classes#include <iostream>#include <fstream>#include <sstream>using namespace std;

int main() {ifstream ifs(“in.txt”);if (ifs.is_open()) {string line1, word1;getline(ifs, line1);istringstream iss(line1);iss >> word1;cout << word1 << endl;

}return 0;

}

• <sstream> header file– Use istringstream for input– Use ostringstream for output

• Useful for scanning input– Get a line from file into string– Wrap string in a stream– Pull words off the stream

• Useful for formatting output– Use string as format buffer– Wrap string in a stream– Push formatted values into

stream– Output formatted string to file