C++ Programming/Example Using User Input

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

[edit] A Program Using User Input

The following program inputs two numbers from the user and prints their sum:

 #include <iostream>
 
 int main()
 {
    int num1, num2;
    std::cout << "Enter number 1: ";
    std::cin >> num1;
    std::cout << "Enter number 2: ";
    std::cin >> num2;
    std::cout << "The sum of " << num1 << " and " << num2 << " is "
               << num1 + num2 << ".\n";
    return 0;
 }

Just like std::cout which represents the standard output stream, the C++ library provides (and the iostream header declares) the object std::cin representing standard input, which usually gets input from the keyboard. The statement:

 std::cin >> num1;

uses the extraction operator (>>) to get an integer input from the user. When used to input integers, any leading whitespace is skipped, a sequence of valid digits optionally preceded by a + or - sign is read and the value stored in the variable. Any remaining characters in the user input are not consumed. These would be considered next time some input operation is performed.

If you want the program to use a function from a specific namespace, normally you must specify which namespace the function is in. The above example calls to cout, which is a member of the std namespace (hence std::cout). If you want a program to specifically use the std namespace for an identifier, which essentially removes the need for all future scope resolution (e.g. std::), you could write the above program like this:

#include <iostream>
 
using namespace std;
 
int main()
{
    int num1, num2;
    cout << "Enter number 1: ";
    cin >> num1;
    cout << "Enter number 2: ";
    cin >> num2;
    cout << "The sum of " << num1 << " and " << num2 << " is "
               << num1 + num2 << ".\n";
    return 0;
}

Please note that 'std' namespace is the namespace defined by standard C++ library.