Standard Input

Introduction

Standard Input1 in C++ is none other than input from the console2. It's syntax is almost identical with Standard Output3, with the exceptions that it uses a different operator, >>, and that you can only pass variables to it4.

How to use it

Let's take a look at a simple example:

#include <iostream>
 
int main()
{
    int input;
 
    std::cout << "Input an integer: ";
    std::cin >> input;
    std::cout << "Your number was: " << input << std::endl;
}

std::cin takes the integer typed by the user and saves it into the variable input.

Usability

Just like std::cout, it can be used with all the primitive types that the language provides, as well as any other class if it has provided the appropriate overloaded operator5, for example std::string.

Get the whole line

There are times you want to take the whole line that the user inputted, and not just a single word. This can be done with the function std::getline(). It takes as parameters an input stream6 and a string. It saves the inputted line inside the string. For example:

#include <iostream>
 
int main()
{
    std::string input;
 
    std::cout << "Type your full name:" << std::endl;
    std::getline(std::cin, input);
    std::cout << "Your name is " << input << std::endl;
}

It can also be passed a third parameter, a character, if you want to customize when it should stop reading.

Conclusion

We've barely scratched the surface with this one. There is still much to learn about it, for example how to recover from erroneous input7, or how to input integers of a different base than decimal8. Be sure to practice as much as you can and like!

Have fun coding ;-)

Next tutorial will be about Functions. Breaking the program into smaller, manageable pieces is essential and considered good practice.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 3.0 License