C++ cheat sheet Comments: // comments up to end of line /* comment continues up to next */ Data types we use most often: int: 1, -7, 1342 float, double: -1.1, 3.1415 bool: true, false char: 'a', '0', ' ', 'Q', '\n' string: "", "Hello, world!" (requires library) constants: const double PI = 3.1415926; reference variables: have an ampersand (&) after the data type reference to an int: int& num reference to an ostream: ostream& file Data type string: requires library can use s[ndx] to get/set character at position ndx can use s.at(ndx) to get/set character at position ndx can use s.c_str() to convert s to a C-style string s.length() returns length of string Style conventions: no tabs four spaces per indent level only indent after line with { only un-indent on line starting with } lines start at same column as previous line is no indent or un-indent switch statements special case for indentation variable names should start with a lower-case letter constant names should be all upper-case Basic program template: /* Documentation comments */ #include directives using namespace std; // Function prototypes go before main int main() { // main code return 0; } // Function implementations go after main Operators: = * / % + - ++ -- Relational: < <= > >= == != Logical: ! && || Input, output (requires library): cin >> variable; // reads in one variable if (!cin) { // check for input error getline(cin, stringVariable); // reads in line including whitespace cin.ignore(); // needed after cin when using getline cin.ignore(1000, '\n'); // flushes input buffer up through newline cout << value << variable; // displays values a loop is required for proper input validation cin << skipws; // used to skip leading whitespace in stream Output formatting (setfill, setw, setprecision require library): left, right fixed, showpoint setprecision(int) setfill(char) setw(int) // only valid for next item displayed Random numbers (requires , ): srand(time(NULL)); // seeds (initializes) random number generator rand() % (high - low + 1) + low // gets random int from low through high Selection: if (test) { // code to run if test is true } if (test) { // code to run if test is true } else { // code to run if test is false } if (test1) { // code to run if test1 is true } else if (test2) { // code to run if test1 is false and test2 is true } else { // code to run if test1 and test2 are both false } if (test1) { // code to run if test1 is true } else { if (test2) { // code to run if test1 is false and test2 is true } else { // code to run if test1 and test2 are both false } } switch (intExpression) { case intValue1: // code to run if intExpression == intValue1 break; case intValue2: // code to run if intExpression == intValue2 break; default: // code to run if no case was matched } Conditional operator (?:): test ? value1 : value2 Entire expression evaluates to value1 if test is true. Entire expression evaluates to value2 if test is false. Repetition: // initialize test variable while (test) { // code to run while test is true // modify test variable } // initialize test variable do { // code to run while test is true // modify test variable } while (test); for (initCounter; testCounter; modifyCounter) { // code to run while testCounter is true } Functions: returnDataType functionName(paramList) { functionBody } Prototype has ";" in place of body and comes before main. Function definitions usually come after main. paramList is a comma separated list of: dataType variableName The paramList is incoming data The function may return one item using the return statement A void returnDataType means that nothing is returned Functions should ONLY do what they are supposed to and no more. Functions should be designed to do one generalized task well. File I/O (requires library): Basic processing for files: open file check for error opening file process (read/write) file records (often in a loop) close file In the following text, ifile and ofile are just variable names ofstream ofile("abc"); // opens (and clears) new output file named "abc" ofstream ofile("abc", ios::app); // opens new output file named "abc" for appending ifstream ifile("abc"); // opens new input file named "abc" Or, if ofile and ifile already existed as variables: ofile.open("abc"); // opens (and clears) new output file named "abc" ofile.open("abc", ios::app); // opens new output file named "abc" for appending ifile.open("abc"); // opens new input file named "abc" if (!ofile) { // checks for errors with ofile ifile.close(); // closes ifile input files can be used just like cin output files can be used just like cout Binary file I/O ofstream ofile("abc", ios::binary); // opens (and clears) new output file named "abc" fstream ofile("abc", ios::binary | ios::out); // opens new output file named "abc" fstream ifile("abc", ios::binary | ios::in); // opens new input file named "abc" fstream file("abc", ios::binary | ios::out | ios::in); // opens new file named "abc" for input and output In the following, assume rfile is a reference to a random access file rfile.seekg(0L, ios::beg); // sends read pointer to beginning of file rfile.seekg(0L, ios::end); // sends read pointer to end of file long bytes = rfile.tellg(); // returns position of read pointer rfile.seekp(0L, ios::beg); // sends write pointer to beginning of file rfile.seekp(0L, ios::end); // sends write pointer to end of file long bytes = rfile.tellp(); // returns position of write pointer sizeof(record); // returns size in bytes of variable, class, or struct // the following writes rec out to wherever the write pointer is in the file rfile.write((&rec), sizeof(rec)); // the following reads data into rec from wherever the read pointer is in the file rfile.write((&rec), sizeof(rec)); Arrays Declaring an array of 10 ints named num: int num[10]; Declaring and initializing an array of three doubles named dbl: double dbl[] = { 1.23, 3.14159, 42 }; Using a constant to declaring an array of 10 ints named num: const int SIZE = 10; int num[SIZE]; Printing all the elements of the num array: for (int i=0; i<10; i++) { cout << num[i] << ' '; } Adding up all the elements of the num array: int tot = 0; for (int i=0; i<10; i++) { tot = tot + num[i]; } Sending the num array to a function: sumArray(num, SIZE); Writing a function to sum elements of an int array and return total: int sumArray(int ar[], int len) { int tot = 0; for (int i=0; i