/* COMPILE: g++ -std=c++98 -Wall -Wextra -O start.cpp */ // C++ libraries: #include #include // c++ string class /* New names for C libraries: */ /* namespace: use std the most */ /* using declarations specify the scope - simplify use */ using std::cout; using std::cin; using std::endl; using std::string; /* can declare using entire namespace: using namespace std; */ void swap1(int, int); // pass by value, doesn't work void swap2(int *, int *); // pass by reference with pointers void swap3(int &, int &); // pass by reference w/aliasing int main() { std::cout << "Hello World"; std::cout << std::endl; int age; std::cout << "what is your age? "; std::cin >> age; std::cout << "enjoy the heat, " << age << " year-old" << std::endl; cout << "woohoo" << endl; /* WORKING WITH OBJECTS */ string s1 = "blah"; string name; string s2("blahblah"); // constructor call string s3(s2); // copy constructor string spaces(10, ' '); // ten spaces cout << "enter name: "; cin >> name; // stops at whitespace cout << "enter text: "; string text; getline(cin, text); // read to end of line, including spaces s3 = s1 + ' ' + s2; // "blah blahblah" text += name; s1 = s2; // deep copy cout << s1.length() << " " << s1.size() << endl; cout << s1.capacity() << endl; cout << s3.substr(3, 5) << endl; // h bla if (s1.compare(s2) < 0) cout << "s1 < s2" << endl; if (s1 < s2) // < > <= >= == != cout << "s1 < s2" << endl; s1 = "cat"; cout << s1.at(1) << endl; // 'a' - does range checking s1.at(1) = 'o'; cout << s1 << " " << s1[1] << endl; // cot o s1[0] = 'C'; /* WORKING WITH PRIMITIVES */ int num1, num2 = 6; bool flag = true; // any non-zero is true, zero is false double d1 = 13.55; num1 = (int) d1; num1 = int(d1); num1 = static_cast(d1); swap1(num1, num2); // call by value cout << "enter 2 ints and 1 double: "; cin >> num1 >> num2 >> d1; swap2(&num1, &num2); // pass the address to pointers cout << num1 << " " << num2 << endl; cout << "enter 2 ints and 1 double: "; cin >> num1 >> num2 >> d1; swap3(num1, num2); // pass to aliases cout << num1 << " " << num2 << endl; int &num3 = num1; // num3 is alias for num1 num3 = 234; cout << num1 << endl; // 234 cout << "enter pairs of grades and max points:" << endl; int grade, maxp; int totalgrade = 0, totalmax = 0; while (cin >> grade >> maxp) { totalgrade += grade; totalmax += maxp; } double avg = (double) totalgrade / totalmax * 100; cout << "homework average is " << avg << endl; char ch; cin.get(ch); // read next character /* auto buffer flushing: at end of line (endl, '\n') if buffer full when read encountered */ cout << std::flush; } void swap1(int a, int b) // pass by value, doesn't work { int temp = a; a = b; b = temp; } void swap2(int *ap, int *bp) // pass by reference with pointers { int temp = *ap; *ap = *bp; *bp = temp; } void swap3(int &aa, int &ba) // pass by reference w/aliasing { int temp = aa; aa = ba; ba = temp; }