Notes for Oct 21

cin-issue.cpp

// Some people had an issue with a regular cin
// (of a number) followed by getline (a string).
// This is because the "input cursor" is left on
// the previous line after the cin, so the getline
// just reads an empty string.
// A solution is to use the "ws" manipulator.

#include <iostream>
using namespace std;

int main()
{
    int quantity;
    string name;
    cout << "Enter quantity: ";
    cin >> quantity;
    cout << "Enter your name: ";
    // If you comment out the following statement,
    // the program won't wait for user to type something,
    // it just moves on with name set to empty string!
    cin >> ws;
    getline(cin, name);
    cout << "Welcome, '" << name << "', quantity is " << quantity << endl;
    return 0;
}

collatz.cpp

// Testing the collatz conjecture --
// a demo of a while loop
#include <iostream>
using namespace std;
int main()
{
    cout << "Enter starting number: ";
    int n;
    cin >> n;
    while(n != 1)
    {
        cout << n << endl;
        if(n%2 == 1) // odd number
        {
            n = 3*n + 1;
        }
        else
        {
            n /= 2;  // divide by two
        }
    }
    cout << "1 and DONE!\n";
    return 0;
}