Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 3: Keyboard Input and Mathematical Expressions

Keyboard Input and Mathematical Expressions

Keyboard Input from the Console

  • cin is an object that is used to read input from the keyboard. The extraction operator (>>) is used with cin and a variable. This statement:
    cin >> x;

    will cause the program to go to the input buffer and take the first data it finds there (up until the first white space that it encounters) and put that value it into the variable x.The way data gets into the input buffer is by the user typing at the keyboard and then hitting the Return key. Whatever they typed at the keyboard is sent to the input buffer. The data just sits there and waits until a statement is executed that will use it. When the above statement using cin is executed, the compiler will go to the input buffer and use the data it finds there for giving a variable a value. If there is no data in the input buffer the program will just sit there and wait. And wait. And wait. You’ll have to enter something or press Control-C to cancel the program and return to the operating system.If the user typed 3.3 and hit return the value 3.3 would be in the input buffer. When the statement above is executed, the compiler will find the value 3.3 and put it into the variable x.

    You can do this for several variables at one time:

    cin >> x >> y >> z;

    The extraction operator (>>) separates each variable in which input is to be stored. If the user types this at the keyboard:

    3.3 4.4 5.5

    and then hits the return key, then the variable x will now have the value of 3.3, the variable y will now have the value of 4.4, and the variable z will now have the value of 5.5.

    It is important to remember that with a cin statement, the only thing that can be on the right hand side of the extraction operator (>>) is a variable.

Using CStrings for i/o

  • A String is a series of characters, such as a word or a line of text. There is no simple string datatype in C++, so there are two ways to store strings: cstrings and the string class.
  • The string class is covered in CS 110B, because it is part of object-oriented programming.
  • The cstring is an older structure for storing strings. It’s used in C as well as C++, so it is valuable to know. A cstring is simply an array of characters that is terminated by a null character (‘\0′). We’ll learn more about what that means later. But for now, here are the basics to allow you to input and output cstrings.
  • When you declare a cstring, you must declare the maximum number of characters it can store, plus an extra character for the end marker. E.g. to declare myString so it can store up to 50 characters:
        char myString[51];
  • Then you can input and output a cstring like any other dataype:
        cin >> myString;
    // works fine to input and output a word of 50 or fewer characters
    cout << myString;
  • Don’t try to use operators like
    <strong> = </strong>


    <strong> == </strong>

    with cstrings. They won’t work. But feel free to use them for simple i/o like described above.

  • We’ll cover more detail about cstrings after we cover arrays.
  • Echo.cpp: Here is an example demonstrating the use of cstring variables, and of the cin object for console input.
  • In-class exercise: input user’s first name, then last name, and store them into two separate variables. Output them in reverse order with a comma between them.
  • name.cpp: Solution to above exercise

Mathematical Functions

  • function – like in algebra, a function can take input (arguments) and produce output (return value). It performs a calculation or executes other code. We’ll write our own functions later, but for now we are going to use pre-defined functions.
  • function call – a line of code that executes a function
  • arguments – the data passed into a function when it is called. Also called actual parameters
  • return value – the “answer” produced by the function, returned from it to the function call.
  • pow function – pre-defined mathematical function to calculate an exponent. For example, to store in the variable x the result of 2 to the 3rd power:
       x = pow(2.0, 3);
  • Another useful mathematical function is sqrt, which returns the square root of a number. Several others are available as well. Full documentation is at
  • To use these mathematical functions, you need to have the following line at the top of your program:

Type Casting

  • Type Cast – an expression to make a value look like it has a different datatype. Type casting never changes the datatype of a variable — that’s impossible. Instead, a type cast is like a function that returns the same value in a different datatype.
  • Old Notation – The old notation for type casts uses the type name only. E.g. to cast the variable x to type double, you could write:



  • New Notation – There is a new notation for type casts which uses the keyword “static_cast” E.g. to cast the variable x to type double, you write:

  • Any of the above notations should work on an up-to-date C++ compiler, but try to get used to the new notation and use that one.
  • Example use of casting: avoiding truncation in integer division. Remember that the result of a division operation will be truncated to an integer if both the operands were integers. So to get an accurate floating point result, cast one of the operands to a floating-point type. So for example when finding the average word length in a document:
      #include <iostream>
      using namespace std;
      int main()
        int num_chars, num_words;
        float avg_length;
        cout << "How many characters are in the document? ";
        cin >> num_chars;
        cout << "and how many words are there? ";
        cin >> num_words;
        avg_length = static_cast<float>(num_chars) / num_words;
        cout << "The average word length is " << avg_length << " characters.\n";
        return 0;
      /* Sample Output:
      How many characters are in the document? 100
      and how many words are there? 28
      The average word length is 3.57143 characters.
      // without the type cast, the average word
      // length calculated would have been 3


  • A constant is a named location in memory that has a datatype (just like a variable) except that its value cannot be changed after it is initialized. Use the keyword const before the datatype to declare a constant.

Shortcut Operators

  • 1

    adds a value to a variable. Similarly, to subtract from or multiply or divide by a value, or take the modulus of a value, use:







  • 1

    increments a variable. So


    is equivalent to

    x += 1;


    x = x + 1;
  • 1

    decrements a variable

In-class exercise: You’re planning a wedding, and you need to transport all your wedding guests from the ceremony to the reception. A bus can carry 40 passengers. Please use a named constant for this value. Your program should ask the user how many guests are expected, and it should output how many busses are needed, and the number of extra people you could carry with those busses. You might want to use the “ceil” function which is defined in <cmath>

busses.cpp: Solution to above in-class exercise