#include <iostream>
using namespace std;
main()
{
/* comments can be one separate line */
cout << "Hello World"; // the compiler will ignore this in-line comment
/* C++ comments can also
* take up multiple lines
* like this one.
*/
return 0;
}
/* Comparison operators return booleans (true/false values) */ /* is x equal to y */ x == y /* is x not equal to y */ x != y /* is x greater than y */ x > y /* is x greater than or equal to y */ x >= y /* is x less than y */ x < y /* is x less than or equal to y */ x <= y
/* Remember to include the following line at the top of your program */
#include <cmath>
/* Operators: */
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
/* Examples: */
int z = x + y;
int w = x * y;
/* Increment (add one) */
x++
/* Decrement (subtract one) */
x--
/* Absolute value */
double value = double abs(double x)
/* Square Root */
double sqrt = double sqrt(double x)
/* Rounding */
int rounded = round(5.86)
/* Example */
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// round
cout << "round(+3.14) = " << round(3.14)
}
// will print out "round(+3.14) = 3"
/* To use strings, you need to import strings, however
they are included in the iostream import.*/
#include <string>
/* Strings are mutable, so you can change a string
without rebuilding it. */
string str = "Hello";
// Access and update with [ ] or .at()
char firstLetter = str[0];
char secondLetter = str.at(1);
// When updating, replace with a char
str[1] = 'E'; // str is now HEllo
str.at(4) = 'O'; // str is now HEllO
// Insert adds string to middle of a string
// str.insert(position, string);
// Example
string str = "Word";
str.insert(3, "l"); // str is now World
/* Substrings are overloaded with two options:
str.substr(index) Substring from the index to the end
str.substr(index, length) Substring from the index for
a specified length */
// Examples
string str = "Hello World";
str.substr(6); // returns "World"
str.substr(3, 2); // returns "lo"
// Find the length of a string with either
// length or size
str.length(); // returns 11
str.size(); // returns 11
/* The find function returns the first position
that the search string is found (case sensitive),
or string::npos if the string is not found. */
str = "Hello World";
str.find("lo"); // returns 3
str.find("hello") // returns string::npos
if (str.find("hello") != string::npos) {
cout << "Found" << endl;
}
else {
cout << "Not found" << endl;
}
#include <iostream>
using namespace std;
// function declaration
int min(int num1, int num2);
int main()
{
// local variable declaration
int a = 100;
int b = 200;
int minimum;
// calling the min function
minimum = min(a, b);
cout << "The minimum value is: " << minimum << endl;
return 0;
}
// function returning the minimum of two numbers
int min(int num1, int num2)
{
// local variable declaration
int result;
if (num1 < num2) {
result = num1;
}
else {
result = num2;
}
return result;
}
// Basic Try/Catch Block
try {
// Block of code to execute that may
// cause an error
}
catch (error type) {
// Block of code to execute if the error type
// is generated
}
// Example: Validating a number
try {
/* Attempt to convert to a number. If the input
* is a number, it will work, otherwise it will
* throw an invalid_argument error.*/
num = stoi(line);
}
catch (invalid_argument) {
isValid = false;
cout << "Not an integer, try again." << endl;
}
if (boolean_expression)
{
// this will execute if the boolean expression is true
}
else
{
// this will execute if the boolean expression is false
}
// example
#include <iostream>
using namespace std;
int main()
{
// local variable declaration
int a = 1;
// check boolean condition
if (a < 100)
{
// if condition is true then print the next line
cout << "a is less than 100;" << endl;
}
else
{
// if condition is false then print the next line
cout << "a is not less than 100;" << endl;
}
cout << "a is equal to: " << a << endl;
return 0;
}
/* while loop syntax */
while (condition) {
statement(s);
}
/* while loop example */
#include <iostream>
using namespace std;
int main()
{
int a = 1;
// while loop execution
while (a < 100)
{
cout << "a is still less than 100! a is: " << a << endl;
a++;
}
return 0;
}
/* for loop syntax */
for (initialize; condition; increment) {
statement(s);
}
/* for loop example */
#include <iostream>
using namespace std;
int main()
{
// for loop execution
for (int a = 1; a < 100; a++)
{
cout << "value of a: " << a << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char str[] = "Hello World!";
cout << "Programmers love to say : " << str << endl;
}
There are two main ways to read input from the user.
cin is used to read one token at a time.
getline is used to read an entire line at a time.
#include <iostream>
using namespace std;
int main()
{
// To read an entire line, you use the getline command.
cout << "Please enter a line: ";
// Create a string variable and read in from the user
string line;
getline(cin, line);
// To read a single token, you can use the cin command
cout << "Please enter a token: ";
string name;
cin >> name;
return 0;
}
File input is done by opening a file as an input stream and then
reading in using the getline command. Once
you capture a line, you can then process it before capturing
the next line.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// Create an input file stream
ifstream in;
// Open the file called input.txt
in.open("input.txt");
// Loop to capture all the line.
while (true) {
string line;
// getline reads in our file as a string
getline(in, line);
/* If you try to read a line and
* it fails, you know you are at the
* end of our file and you can break
* out of the loop */
if (in.fail()) break;
// process the results
cout << line << endl;
}
// close our input file stream
in.close();
return 0;
}
File output is done by opening a file as an output stream and then streaminng into the file just like you would stream to the console.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// Create and open the output file
ofstream out;
out.open("output.txt");
// Write to the output file
out << "Hello World!" << endl;
out << "Nice to meet you" << endl;
// Close the file
out.close();
return 0;
}
#include <vector> // Be sure to include vector
/* syntax to declare a vector */
vector<type> vectorName;
/* declare a vector with intial values */
vector<type> vectorName {value, value, ...};
/* Examples */
vector<string> names;
vector<int> ages {13, 15, 14, 14};
/* Add values to the end of a vector*/
names.push_back("Karel");
/* Use an iterator to add at an index
Example: add at index 2 */
vector <string>::iterator it = names.begin();
names.insert(it + 2, "Tracy");
/* Access the third element of a vector */
double third = weights.at(2);
double third = weights[2];
/* Vector size */
int s = ages.size();
/* syntax to declare an array */
type arrayName [ arraySize ];
/* declare a 7-element array called weights */
double weights[7];
/* initialize array */
double weights[5] = {10.0, 200.0, 45.4, 70.0, 99.0};
/* assign 4th elements of the ages array to be 33.0 */
weights[3] = 33.0;
/* index into array to access the third element */
double third = weights[2];
The util.h file can be imported into any C++ program by using
#include "util.h" Below is the header file for the
library.
#include <iostream> #include <vector> using namespace std; // Prints error message and terminates the program void Error(string message); // Prints out prompt and returns string line string readLine(const string prompt = "?"); // Prints out the prompt and returns an integer. If an integer // is not entered (or it is out of the range), the reprompt // is printed and the user can enter again. int readInt(const string prompt = "?", string reprompt = ""); int readInt(const int low, const int high, const string prompt = "?", string reprompt = ""); // Prints out the prompt and returns a double. If a double // is not entered (or it is out of the range), the reprompt // is printed and the user can enter again. double readDouble(const string prompt = "?", string reprompt = ""); double readDouble(const double low, const double high, const string prompt = "?", string reprompt = ""); // Splits a string based on the delimiter and returns a vector vectorsplitLine(string input, char delimeter = ' '); // Returns uppercasw/lowercase version of a string. string toUpperCase(string s); string toLowerCase(string s); // Random number generator. Returns a random integer. // Set seed is optional. void setSeed(int seed); int randInt(); int randInt(int min, int max);