CS 342: Intro to C++ Programming            A Simple C++ Program#include <iostream>using namespace std;int main() {  cout ...
CS 342: Intro to C++ Programming             #include <iostream>• #include tells the precompiler to include a file• Usuall...
CS 342: Intro to C++ Programming           using namespace std;• The using directive tells the compiler to include code  f...
CS 342: Intro to C++ Programming                           int main()• Declares the main function of any C++ program• Here...
CS 342: Intro to C++ Programmingcout<<“hello, world!”<<endl;• Uses the standard output iostream, named cout   – For standa...
CS 342: Intro to C++ Programming  A Slightly Bigger C++ Program#include <iostream>using namespace std;int main(int argc, c...
CS 342: Intro to C++ Programming      int argc, char * argv[]• A way to affect the program’s behavior   – Carry parameters...
CS 342: Intro to C++ Programmingfor(int i = 0; i < argc; ++i)• Standard C++ for loop syntax   – Initialization statement d...
CS 342: Intro to C++ Programming   {cout << argv[i] << endl;}• Body of the for loop• You should use braces, even if there’...
CS 342: Intro to C++ Programming                                C++ Types•    int, long, short, char (integer division)•  ...
CS 342: Intro to C++ Programming      C++ Loops and Conditionals• Loops    – for    – while    – do• Conditionals    – if,...
CS 342: Intro to C++ Programming                      C++ Operators• Relational operators    == <= >= < > !=• Assignment o...
CS 342: Intro to C++ Programming                           C++ Functions• In C++, behavior need not be part of a class    ...
CS 342: Intro to C++ Programming Parameter/Variable Declarations• Read a function parameter or local variable  declaration...
CS 342: Intro to C++ Programming                 Pass By Referencevoid foo() {  int i = 7;                                ...
CS 342: Intro to C++ Programming                       Pass By Valuevoid foo() {  int i = 7;                              ...
CS 342: Intro to C++ Programming          C++ Classes and Structs                                           • Struct membe...
CS 342: Intro to C++ Programming          C++ Classes and StructsWe also need an implementation    – Generally in the .cpp...
CS 342: Intro to C++ Programming                 C++ string Class#include <iostream>                        • <string> hea...
CS 342: Intro to C++ ProgrammingC++ Input/Output Stream Classes#include <iostream>       •                <iostream> heade...
CS 342: Intro to C++ Programming      C++ File I/O Stream Classes#include <fstream>                       • <fstream> head...
CS 342: Intro to C++ Programming         C++ String Stream Classes#include <iostream>                       • <sstream> he...
Upcoming SlideShare
Loading in...5
×

C++ programming intro

294

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
294
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
23
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

C++ programming intro

  1. 1. CS 342: Intro to C++ Programming A Simple C++ Program#include <iostream>using namespace std;int main() { cout << “hello, world!” << endl; return 0;}Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  2. 2. 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  3. 3. 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  4. 4. 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  5. 5. CS 342: Intro to C++ Programmingcout<<“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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  6. 6. 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;}Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  7. 7. 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] Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  8. 8. CS 342: Intro to C++ Programmingfor(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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  9. 9. 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  10. 10. 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  11. 11. CS 342: Intro to C++ Programming C++ Loops and Conditionals• Loops – for – while – do• Conditionals – if, else, else if – ?: operator – switchCopyright © 2004 Dept. of Computer Science and Engineering, Washington University
  12. 12. 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 =Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  13. 13. 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  14. 14. CS 342: Intro to C++ Programming Parameter/Variable Declarations• Read a function parameter or local variable declaration right to left int 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 Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  15. 15. CS 342: Intro to C++ Programming Pass By Referencevoid foo() { int i = 7; local variable i baz (i); 7 ? 3}void baz(int & j) { j = 3; 7 ? 3} j is a reference to the variable passed to bazCopyright © 2004 Dept. of Computer Science and Engineering, Washington University
  16. 16. CS 342: Intro to C++ Programming Pass By Valuevoid foo() { int i = 7; 7 local variable i baz (i);}void baz(int j) { j = 3; local variable j 7 ? 3 (initialized with the value} passed to baz)Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  17. 17. CS 342: Intro to C++ Programming C++ Classes and Structs • Struct members are publicstruct MyData { by default MyData(int i) :m_x(i){} • Class members are int m_x; private by default}; • Both can have – Constructors – Destructorsclass MyObject { – Member variablespublic: – Member functions MyObject(int y); ~MyObject(); • Common practice:private: – use structs for data int m_y; – use classes for objects with methods}; • Declarations usually go in header filesCopyright © 2004 Dept. of Computer Science and Engineering, Washington University
  18. 18. CS 342: Intro to C++ Programming C++ Classes and StructsWe also need an implementation – Generally in the .cpp fileMyObject::MyObject(int y) :m_y(y) { // It’s a good idea to assert your arguments assert(y > 0);}MyObject::~MyObject() {}Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  19. 19. CS 342: Intro to C++ Programming C++ string Class#include <iostream> • <string> header file#include <string>using namespace std; • Various constructorsint main() { – Prata, pp. 780 string s; // empty • Assignment operator s = “”; // empty • Overloaded operators s = “hello”; += + < >= == [] s += “, ”; s = s + “world!”; • The last one is really cout << s << endl; useful: indexes string return 0; if (s[0] == ‘h’) …}Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  20. 20. CS 342: Intro to C++ ProgrammingC++ Input/Output Stream Classes#include <iostream> • <iostream> header fileusing namespace std; – Use istream for input – Use ostream for outputint main() { • Overloaded operators int i; << ostream insertion operator // cout == std ostream >> istream extraction operator cout << “how many?” • Other methods << endl; – ostream: write, put // cin == std istream – istream: get, eof, good, clear cin >> i; • Stream manipulators – ostream: flush, endl, setwidth, cout << “You said ” << i setprecision, hex, boolalpha << ‘.’ << endl; – Prata pp. 891-892 return 0;}Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  21. 21. CS 342: Intro to C++ Programming C++ File I/O Stream Classes#include <fstream> • <fstream> header fileusing namespace std; – Use ifstream for inputint main() { – Use ofstream for output ifstream ifs; ifs.open(“in.txt”); • Other methods ofstream ofs(“out.txt”); – open, is_open, close if (ifs.is_open() && – getline ofs.is_open()) { – seekg, seekp int i; • File modes ifs >> i; – in, out, ate, app, trunc, binary ofs << i; } ifs.close(); ofs.close(); return 0;} Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  22. 22. CS 342: Intro to C++ Programming C++ String Stream Classes#include <iostream> • <sstream> header file#include <fstream> – Use istringstream for input#include <sstream> – Use ostringstream for outputusing namespace std; • Useful for scanning inputint main() { – Get a line from file into string ifstream ifs(“in.txt”); – Wrap string in a stream if (ifs.is_open()) { – Pull words off the stream string line1, word1; • Useful for formatting output getline(ifs, line1); – Use string as format buffer istringstream iss(line1); – Wrap string in a stream iss >> word1; – Push formatted values into cout << word1 << endl; stream } – Output formatted string to file return 0;} Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×