Search⌘ K
AI Features

User Input and Formatting

Explore how to take user input through cin and getline, convert strings to numbers using stoi and stod, and format output using <iomanip>. This lesson guides you to create an interactive point-of-sale system where inputs drive calculations and clean receipt formatting. You'll gain practical skills in handling multi-word inputs, data conversion, and output precision to build user-friendly C++ programs.

The project

We'll revisit the POS system one last time. In our previous lesson, the prices, quantities, and names were typed directly into the C++ code, which worked fine for us as coders.

But here’s the problem: Is the cashier also a coder? No. They don’t want to open code, find variables, and change values; they just want to type the customer’s details and prices into the system while the customer is standing there.

You’ve been hired to create a smarter version of this point-of-sale system, one where the cashier simply enters the quantities and prices at the command line when the app is running, and the program automatically calculates and prints the receipt. The cashier will not need to look at the code.

This is what the receipt looks like:

The programming concept

The programming concept for today is user input.

While we know how to display something to the user using cout function, sometimes we need to fetch some information from the user instead of displaying something to them. The user can use their keyboard to type in the required information.

C++ has another built-in function called cin that lets us ask the user (in this case, the cashier) to type something into the terminal. Whatever they type can then be stored in a variable, just like the ones we learned about ...