Input and output
Problem
The program knows only one name
The program greets the customer by name:
string name = "Maria";Console.WriteLine("Hello, " + name + "!");Hello, Maria!It works, but it greets everyone as Maria. The name is written in the code. For every new customer you have to change the program and run it again. You want the program to ask on its own.
The idea
Reading from the keyboard
When the program reads, it stops and waits. The person types and presses Enter. What they type is the program's input.
class Program{ static void Main() { Console.Write("What is your name? "); string name = Console.ReadLine(); Console.WriteLine("Hello, " + name + "!"); }}MariaWhat is your name? Hello, Maria!Console.ReadLine() reads one line, up to Enter.
The input and the output are shown separately here. In the console the name appears where you type it: after "What is your name? ". That is why the question uses Write: so the answer is on the same line.
More precisely, if you are curious
- In a project from
dotnet new console, the linestring name = Console.ReadLine();gives warning CS8600. The reason is thatReadLinereturnsnull(nothing) if the input has ended. It is a warning, not an error, and the program runs. You will see how to work withnulllater. Console.Read()reads only one character and returns its code as a number. In this course we always read whole lines.
Problem
12 + 30 = 1230
The cashier enters two payments, €12 and €30. The program has to show the total:
string first = Console.ReadLine();string second = Console.ReadLine();string total = first + second;Console.WriteLine("Total: €" + total);1230Total: €1230Instead of 42 you got 1230. The program did not get the math wrong. It did no math at all.
The idea
From text to a number
Whatever the person types, Console.ReadLine() returns text. "12" and "30" are two texts, and + between texts glues them together. To do math, turn the text into a number:
int first = int.Parse(Console.ReadLine());int second = int.Parse(Console.ReadLine());int total = first + second;Console.WriteLine("Total: €" + total);1230Total: €42Turning text into a value of another type is called parsing.
int.Parse(...)gives anint.double.Parse(...)gives adouble.- The other types have the same:
long.Parse,bool.Parseand so on.
The sum here is the first calculation in the course. Subtraction, multiplication and division come in the next lesson.
int first = int.Parse(Console.ReadLine());int second = int.Parse(Console.ReadLine());int total = first + second;Console.WriteLine("Total: €" + total);Step by step, in words
- The person types 12 and Enter. Console.ReadLine() returns the text "12", not a number.
- int.Parse turns the text into the number 12. It goes into first.
- 30 takes the same path: text, parsing, a number in second.
- Now + adds numbers: 12 + 30 = 42.
- It prints "Total: €42".
More precisely, if you are curious
- If the text is not a number (for example "twelve"), the program stops with an error:
FormatException. You will see how to catch such an error in the "Errors and exceptions" module.
int.TryParsechecks without stopping the program. You use it withifandout, which come later.
- The decimal separator depends on the computer's regional settings. On a computer with Bulgarian settings,
double.Parse("3.5")stops with an error and wants a comma:3,5. The examples in this course use a point.
Try it
How many tickets?
The program reads how many adults and how many children there are.
23What will the program print?
int adults = int.Parse(Console.ReadLine());int children = int.Parse(Console.ReadLine());Console.WriteLine("Tickets: " + adults + children);"Tickets: " + adults is already the text "Tickets: 2", and text + 3 glues 3 onto the end. With parentheses the sum is done first: "Tickets: " + (adults + children) gives "Tickets: 5".The idea
Numbers the way you want them
In the last lesson the price 49.90 came out as 49.9. For a price you always want two digits after the decimal point. This is formatted output:
string product = "Headphones";double price = 49.9;int qty = 2;Console.WriteLine($"{product}: €{price:F2}");Console.WriteLine($"{qty} in the cart");string label = $"Price: €{price:F2}";Console.WriteLine(label);Headphones: €49.902 in the cartPrice: €49.90$ in front of the quotes lets you write values right inside the text, in curly braces: {product}. This is called string interpolation.
After a colon you write the format: {price:F2} means a decimal number with exactly 2 digits after the point. F0 has no digits after the point, F3 has three.
The value in the variable does not change. The format only decides how it looks when it is printed.
More precisely, if you are curious
- Thousands separators and lining up in columns:
double total = 1234.5;Console.WriteLine($"Total: €{total:N2}");Console.WriteLine($"{"Coffee",-10}|{2.5,8:F2}");Console.WriteLine($"{"Laptop",-10}|{1299.0,8:F2}");Total: €1,234.50Coffee | 2.50Laptop | 1299.00N2 adds a thousands separator. The number after the comma is the width: {2.5,8:F2} takes 8 characters, aligned right, and -10 aligns left.
There is also an older form with the same meaning: Console.WriteLine("{0}: €{1:F2}", product, price);. You will see it in other people's code.
- Regional settings matter here too. On a computer with Bulgarian settings,
F2gives49,90, and the thousands separator is a space:1 234,50. The output in the lessons uses a point.
In C# even a plain "Price: €" + price follows the settings. On a computer with Bulgarian settings, the price from the last lesson comes out as 49,9.
Try it
Two digits
A night at the hotel costs €65.5. You want it to come out as "Per night: €65.50". What goes in the blank?
Console.WriteLine($"Per night: €{price:}");F2: a decimal number with exactly two digits after the point.
Try it
Find the bug
The program asks how many tickets to reserve. It does not compile. Which line is the bug on?
Pick the line with the bug.
Console.ReadLine() returns text, and tickets is an int. The compiler does not turn text into a number by itself: "CS0029: Cannot implicitly convert type 'string' to 'int'". The fix is int tickets = int.Parse(Console.ReadLine());.Exercise
Programs that ask
Solve the tasks in your editor. The input is one line for each value. Do not print questions like "Enter a name:", so your output matches the sample.
1. Greeting by name. Read a name and greet the person.
MariaHello, Maria!2. Sum of two numbers. Read two whole numbers and print the calculation.
172517 + 25 = 423. Two texts in one. Read two texts and print them together, with a space between them.
VelikoTarnovoVeliko Tarnovo4. π with two digits. Store π in a variable as 3.14159265358979 and print it with two digits after the point. The ready value Math.PI comes in the next lesson.
3.14More tasks
- Age. Read a name and an age (a whole number) and print "Maria is 19 years old."
- A business card from the keyboard. Read a name, a job and a phone number and print the business card from the "Your first program" lesson with them.
- A price with two digits. Read a price as a decimal number and print it with two digits and the euro sign: for input
7.5the output isPrice: €7.50. - Sum of two prices. Read two decimal prices and print their sum with two digits: for input
12.4and3.15the output isTotal: €15.55.
Test