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 earlier. We can then use this data to make calculations or print it out in a nice format.
In C++, you can read user input like this:
#include <iostream>
using namespace std;
int main() {
string name;
cout << "What is your name? " << endl;
cin >> name;
cout << "Hello, " << name << "!" << endl;
return 0;
}But here’s an important detail:
If you want to read multi-word inputs (like Organic Almond Milk), cin alone won’t work—it stops reading after the first space. For that, you’ll use getline() instead:
You’ll also learn about data conversion. cin always reads text (strings), but when you want to do math, you’ll need numbers.
For example, "3" and "3.5" are just strings until you convert them. That’s where conversion functions come in.
stoi()converts a string into an integer (whole number)stod()converts a string into a double (decimal number)
You’ll also revisit output formatting using <iomanip> to make your receipt look neat and professional.
The significance of the concept in the project
In our earlier receipt, values like milk_quantity = 1 and milk_price = 4 were typed into the code itself. This meant that if the price of milk changed, the cashier would need to open the file, locate the correct line, and edit it, which was a slow and error-prone process. In a busy store, this is just not realistic.
With user input, your program becomes interactive. The cashier can simply type:
Enter item name: MilkEnter quantity: 1Enter price: 4
The cashier simply types the required numbers and presses Enter.
The program takes care of the rest, calculating totals, formatting the receipt, and printing it neatly. This saves time, reduces mistakes, and means that once the code is written, it never needs to be touched for everyday sales.
Concept at a glance:
cinreads single-word input.getline()reads a full line of text, including spaces.stoi()andstod()convert text input to integers and doubles for math operations.<iomanip>lets you format decimal output to look clean and currency-like.
Learn to code the concept
Let’s start with just the milk example. Instead of writing values directly, we’ll ask the user to enter them:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
// Variables
int milk_qty;
double milk_price;
// --- User Inputs ---
cout << "\nEnter quantity of Milk: ";
cin >> milk_qty;
cout << "Enter price of Milk: ";
cin >> milk_price;
// --- Calculations ---
double total_bill = milk_qty * milk_price;
// --- Output Receipt ---
cout << fixed << setprecision(2);
cout << "Total bill: " << total_bill << endl;
return 0;
}Now, the cashier can type any quantity and price, and the program calculates the correct total instantly; no code editing is needed.
Learn to code with AI
Now that we know how to take input from the user, let’s revisit our full receipt idea:
=== MART RECEIPT ===Cashier Name: AlexItems Purchased:Milk (1): 4Bread (1): 2Eggs (12): 0.5 x 12 = 6Total bill: 4 + 2 + 6 = 12
We’ve coded for milk and its bill, but let’s code for the complete receipt. We’ll need inputs for the cashier’s name and for each item’s quantity and price. The program should calculate subtotals, sum them to determine the total bill, and print the results in the neat receipt style shown above.
Generate code with AI
We don’t want to exaggerate the whole idea of using AI to generate code for us.
Modern-day entrepreneurial dreams depend on knowing how to effectively guide AI. We should treat our AI co-partners like well-read, well-educated individuals. We must be specific in our requests, clear in our expectations, and provide all necessary details.
Here’s a prompt you can use with your AI copilot:
Write a C++ program that reads item names, quantities, and prices from user input,then calculates and prints a receipt like this:=== MART RECEIPT ===Cashier Name: AlexItems Purchased:Milk (1): 4Bread (1): 2Eggs (12): 0.5 x 12 = 6Total bill: 4 + 2 + 6 = 12I’ve started with code that reads a single item’s name, quantity, and price using getline() and cin.Please complete it to handle multiple items and calculate the total automatically.
Write your prompt in Copilot:
Test code with AI
Once the AI has generated the code, copy and paste it into the code widget below, run it, and test different scenarios. Try changing quantities and prices to see if the receipt updates correctly. Make sure your formatting matches the sample output exactly.
// Paste your code here
If the code does not work and you’re stuck, try first to diagnose why it isn’t working. If that fails, try the Ask AI Mentor button. If that also doesn’t help you get unstuck, go back to the Copilot and have a chat with it, telling it the problem you faced with the code it generated.
If all else fails, click the “Show Solution” button.
Food for thought
What happens if you press Enter without typing anything?
Why does
getline()work better thancinfor names with spaces?What happens if you forget to convert string input to numbers before doing math?
Practice makes perfect
The more you work with cin, getline(), and setprecision(), the more natural it becomes to treat code like a two-way conversation between humans and computers.
Try expanding your receipt:
Add a discount input from the cashier.
Ask for cashier name from the user.
Ask for the store name and print it at the top.
Format columns neatly using
<iomanip>manipulators likesetw().
Problem
This is the new requirement. You have to write the code that adjusts the discount on the bill:
If you’re unsure how to do this, click the “Show Hint” button.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
// Variables
int milk_qty, bread_qty, eggs_qty;
double milk_price, bread_price, egg_price;
// --- User Inputs ---
cout << "\nEnter quantity of Milk: ";
cin >> milk_qty;
cout << "Enter price of Milk: ";
cin >> milk_price;
cout << "\nEnter quantity of Bread: ";
cin >> bread_qty;
cout << "Enter price of Bread: ";
cin >> bread_price;
cout << "\nEnter quantity of Eggs: ";
cin >> eggs_qty;
cout << "Enter price of one Egg: ";
cin >> egg_price;
// --- Calculations ---
double milk_total = milk_qty * milk_price;
double bread_total = bread_qty * bread_price;
double eggs_total = eggs_qty * egg_price;
double total_bill = milk_total + bread_total + eggs_total;
// --- Output Receipt ---
cout << fixed << setprecision(2);
cout << "\n=== MART RECEIPT ===" << endl;
cout << "Cashier Name: Alex" << endl;
cout << "Items Purchased:" << endl;
cout << "Milk (" << milk_qty << "): " << milk_total << endl;
cout << "Bread (" << bread_qty << "): " << bread_total << endl;
cout << "Eggs (" << eggs_qty << "): " << egg_price
<< " x " << eggs_qty << " = " << eggs_total << endl << endl;
cout << "Total bill: "
<< milk_total << " + " << bread_total << " + " << eggs_total
<< " = " << total_bill << endl;
return 0;
}Add the discount feature so the program matches the sample output exactly.
If you’re stuck, click the “Show Solution” button.
Congratulations. By now, you’ve learned how to print, take input, and perform mathematical operations to make a realistic POS app. Press Continue to keep learning. In the next chapter, we’ll make a new app.