Console Input

When using std::cout, we’re performing console output since, well, text is being outputted to the computer’s console, or screen. We can actually do the opposite of that in C++ and perform console input. This means taking text in the computer’s console and inputting that into our program. For this, we use std::cin.

Here’s what this looks like in a program:

#include <iostream>
#include <string>

int main() {
  std::cout << "Enter your name: ";
  std::string name;
  std::cin >> name;
  std::cout << "Your name is: " << name << "\n";
  return 0;
}

Note: std::cin uses two greater than signs (>>), rather than two less than signs like for std::cout. Generally, the “>>” symbol is called the stream insertion operator because it’s used to represent text insertion or input.

Using std::cin causes the program to wait for some input to be entered into the console (followed by the enter key). In the program above, this input is then stored into the name variable, allowing it to be used later.

std::cin also works with other data types, like int:

#include <iostream>

int main() {
  std::cout << "Enter a number: ";
  int number;
  std::cin >> number;
  std::cout << "Your number is: " << number << "\n";
  return 0;
}

With console input, our programs can become much more useful and interactive. Here’s a quadratic formula calculator, for example:

#include <iostream>
#include <cmath> //Needed for std::sqrt function

int main() {
  std::cout << "ax^2 + bx + c = 0\n";
  
  std::cout << "a: ";
  double a;
  std::cin >> a;

  std::cout << "b: ";
  double b;
  std::cin >> b;

  std::cout << "c: ";
  double c;
  std::cin >> c;

  double squareRoot = std::sqrt(b * b - 4 * a * c);
  double solution1 = (-b + squareRoot) / (2 * a);
  double solution2 = (-b - squareRoot) / (2 * a);

  std::cout << "x = " << solution1 << " or " << solution2 << "\n";
  return 0;
}

std::getline

If you try entering your full name in the first example program on this page, you’ll see that the program only reads your first name. That’s because std::cin only reads an input up to the first space or new line (i.e. ‘\n’) in that input. To read a full line of text (up to the newline character), we can use std::getline.

To do so, the line:

std::cin >> name;

just needs to be replaced with:

std::getline(std::cin, name);

Therefore, that full program would look like this:

#include <iostream>
#include <string>

int main() {
  std::cout << "Enter your name: ";
  std::string name;
  std::getline(std::cin, name);
  std::cout << "Your name is: " << name << "\n";
  return 0;
}

Challenge Problem

Create a program that asks the user to enter some text (read the text using std::getline). Then, display the input text, reversed.

If you get stuck, check out my solution here.