SlideShare a Scribd company logo
Console Input / Output
Reading and Writing to the Console
Svetlin Nakov
Technical Trainer
www.nakov.com
Software University
http://softuni.bg
2
1. Printing to the Console
ο‚§ Printing Strings and Numbers
2. Reading from the Console
ο‚§ Reading Characters
ο‚§ Reading Strings
ο‚§ Parsing Strings to Numeral Types
ο‚§ Reading Numeral Types
3. Various Examples
Table of Contents
Printing to the Console
Printing Strings, Numeral Types
and Expressions
4
ο‚§ The console (terminal window) is used to read / display text-
based information in a virtual terminal window
ο‚§ Learn more from Wikipedia: terminal emulator, virtual console
ο‚§ Can display different values:
ο‚§ Strings
ο‚§ Numeral types
ο‚§ All primitive data types
ο‚§ To print to the console use the
Console class (System.Console)
Printing to the Console
5
ο‚§ Provides methods for console input and output
ο‚§ Input
ο‚§ Read(…) – reads a single character
ο‚§ ReadKey(…) – reads a combination of keys
ο‚§ ReadLine(…) – reads a single line of characters
ο‚§ Output
ο‚§ Write(…) – prints the specified argument on the console
ο‚§ WriteLine(…) – prints specified data to the console and moves
to the next line
The Console Class
6
ο‚§ Printing an integer variable:
ο‚§ Printing more than one variable using a formatting string:
Console.Write(…)
int a = 15;
Console.Write(a); // 15
double a = 15.5;
int b = 14;
...
Console.Write("{0} + {1} = {2}", a, b, a + b);
// 15.5 + 14 = 29.5
ο‚§ The next print operation will start from the same line
7
Console.WriteLine(…)
ο‚§ Printing more than one variable using a formatting string:
string str = "Hello C#!";
Console.WriteLine(str);
ο‚§ Printing a string variable + new line (rn):
string name = "Marry";
int year = 1987;
...
Console.WriteLine("{0} was born in {1}.", name, year);
// Marry was born in 1987.
ο‚§ Next printing will start from the new line
8
Printing to the Console – Example
static void Main()
{
string name = "Peter";
int age = 18;
string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",
name, age, town);
// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");
Console.WriteLine("Next sentence will be on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.", name, town);
}
ο‚§ index
ο‚§ The zero-based index of the argument whose string
representation is to be included at this position in the string
ο‚§ alignment
ο‚§ A signed integer that indicates the total length of the field into
which the argument is inserted
ο‚§ a positive integer – right-aligned
ο‚§ a negative integer – left-aligned
Formatting Strings
{index[,alignment][:formatString]}
ο‚§ formatString
ο‚§ Specifies the format of the corresponding argument's result string,
e.g. "X", "C", "0.00", e.g.
Formatting Strings (2)
static void Main()
{
double pi = 1.234;
Console.WriteLine("{0:0.000000}", pi);
// 1.234000
}
{index[,alignment][:formatString]}
11
Formatting Strings – Examples
static void Main()
{
int a=2, b=3;
Console.Write("{0} + {1} =", a, b);
Console.WriteLine(" {0}", a+b);
// 2 + 3 = 5
Console.WriteLine("{0} * {1} = {2}", a, b, a*b);
// 2 * 3 = 6
float pi = 3.14159206;
Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14
Console.WriteLine("Bye – Bye!");
}
12
Printing a Menu – Example
double colaPrice = 1.20;
string cola = "Coca Cola";
double fantaPrice = 1.20;
string fanta = "Fanta Dizzy";
double zagorkaPrice = 1.50;
string zagorka = "Zagorka";
Console.WriteLine("Menu:");
Console.WriteLine("1. {0} – {1}", cola, colaPrice);
Console.WriteLine("2. {0} – {1}", fanta, fantaPrice);
Console.WriteLine("3. {0} – {1}", zagorka, zagorkaPrice);
Console.WriteLine("Have a nice day!");
Printing to
the Console
Live Demo
Reading from the Console
Reading Strings and Numeral Types
15
ο‚§ We use the console to read information from the command line
ο‚§ Usually the data is entered from the keyboard
ο‚§ We can read:
ο‚§ Characters
ο‚§ Strings
ο‚§ Numeral types (after conversion)
ο‚§ To read from the console we use the methods
Console.Read() and Console.ReadLine()
Reading from the Console
16
ο‚§ Gets a single character from the console (after [Enter] is
pressed)
ο‚§ Returns a result of type int
ο‚§ Returns -1 if there aren’t more symbols
ο‚§ To get the actually read character we need to cast it to char
Console.Read()
int i = Console.Read();
char ch = (char) i; // Cast the int to char
// Gets the code of the entered symbol
Console.WriteLine("The code of '{0}' is {1}.", ch, i);
Reading Characters
from the Console
Live Demo
18
ο‚§ Waits until a combination of keys is pressed
ο‚§ Reads a single character from console or a combination of keys
ο‚§ Returns a result of type ConsoleKeyInfo
ο‚§ KeyChar – holds the entered character
ο‚§ Modifiers – holds the state of [Ctrl], [Alt], …
Console.ReadKey()
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Character entered: " + key.KeyChar);
Console.WriteLine("Special keys: " + key.Modifiers);
Reading Keys from the Console
Live Demo
20
ο‚§ Gets a line of characters
ο‚§ Returns a string value
ο‚§ Returns null if the end of the input is reached
Console.ReadLine()
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
Reading Strings from the Console
Live Demo
22
ο‚§ Numeral types can not be read directly from the console
ο‚§ To read a numeral type do the following:
1. Read a string value
2. Convert (parse) it to the required numeral type
ο‚§ int.Parse(string)
ο‚§ Parses (converts) a string to int
Reading Numeral Types
string str = Console.ReadLine()
int number = int.Parse(str);
Console.WriteLine("You entered: {0}", number);
23
ο‚§ Numeral types have a method Parse(…)
for extracting the numeral value from a string
ο‚§ int.Parse(string) – string οƒ  int
ο‚§ long.Parse(string) – string οƒ  long
ο‚§ float.Parse(string) – string οƒ  float
ο‚§ Causes FormatException in case of error
Converting Strings to Numbers
string s = "123";
int i = int.Parse(s); // i = 123
long l = long.Parse(s); // l = 123L
string invalid = "xxx1845";
int value = int.Parse(invalid); // FormatException
24
Reading Numbers from the Console – Example
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}", a, b, a+b);
Console.WriteLine("{0} * {1} = {2}", a, b, a*b);
float f = float.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);
}
25
ο‚§ Converting can also be done through the Convert class
ο‚§ Convert.ToInt32(string[, base]) – string οƒ  int
ο‚§ Convert.ToSingle(string)– string οƒ  float
ο‚§ Convert.ToInt64(string)– string οƒ  long
ο‚§ It uses the parse methods of the numeral types
Converting Strings to Numbers (2)
string s = "123";
int i = Convert.ToInt32(s); // i = 123
long l = Convert.ToInt64(s); // l = 123L
string invalid = "xxx1845";
int value = Convert.ToInt32(invalid); // FormatException
Reading Numbers from the Console
Live Demo
27
ο‚§ Sometimes we want to handle the errors when parsing a number
ο‚§ Two options: use try-catch block or TryParse()
ο‚§ Parsing with TryParse():
Error Handling when Parsing
string str = Console.ReadLine();
int number;
if (int.TryParse(str, out number))
{
Console.WriteLine("Valid number: {0}", number);
}
else
{
Console.WriteLine("Invalid number: {0}", str);
}
Parsing with TryParse()
Live Demo
Regional Settings
Printing and Reading Special Characters
Regional Settings and the Number Formatting
30
ο‚§ Printing special characters on the console needs two steps:
ο‚§ Change the console properties
to enable Unicode-friendly font
ο‚§ Enable Unicode for the Console
by adjusting its output encoding
ο‚§ Prefer UTF8 (Unicode)
How to Print Special Characters on the Console?
using System.Text;
…
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Π’ΠΎΠ²Π° Π΅ ΠΊΠΈΡ€ΠΈΠ»ΠΈΡ†Π°: ☺");
31
ο‚§ The currency format and number formats are different in
different countries
ο‚§ E.g. the decimal separator could be "." or ","
ο‚§ To ensure the decimal separator is "." use the following code:
Decimal Separator
using System.Threading;
using System.Globalization;
…
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(3.54); // 3.54
decimal value = decimal.Parse("1.33");
Regional Settings
Live Demo
Reading and Printing to the Console
Various Examples
34
Printing a Letter – Example
Console.Write("Enter person name: ");
string person = Console.ReadLine();
Console.Write("Enter company name: ");
string company = Console.ReadLine();
Console.WriteLine(" Dear {0},", person);
Console.WriteLine("We are pleased to tell you that " +
"{1} has accepted you to take part in the "C# Basics"" +
" course. {1} wishes you a good luck!", person, company);
Console.WriteLine(" Yours,");
Console.WriteLine(" {0}", company);
Printing a Letter
Live Demo
36
Calculating Area – Example
Console.WriteLine("This program calculates " +
"the area of a rectangle or a triangle");
Console.Write("Enter a and b (for rectangle) " +
" or a and h (for triangle): ");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.Write("Enter 1 for a rectangle or 2 for a triangle: ");
int choice = int.Parse(Console.ReadLine());
double area = (double) (a*b) / choice;
Console.WriteLine("The area of your figure is {0}", area);
Calculating Area
Live Demo
38
ο‚§ Basic input and output methods of the class Console
ο‚§ Write(…) and WriteLine(…)
ο‚§ Write values to the console
ο‚§ Read(…) and ReadLine(…)
ο‚§ Read values from the console
ο‚§ Parsing numbers to strings
ο‚§ int.Parse(…)
ο‚§ double.Parse(…)
ο‚§ …
Summary
?
http://softuni.bg/courses/csharp-basics/
Console Input / Output
License
ο‚§ This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
40
ο‚§ Attribution: this work may contain portions from
ο‚§ "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license
ο‚§ "C# Part I" course by Telerik Academy under CC-BY-NC-SA license
Free Trainings @ Software University
ο‚§ Software University Foundation – softuni.org
ο‚§ Software University – High-Quality Education,
Profession and Job for Software Developers
ο‚§ softuni.bg
ο‚§ Software University @ Facebook
ο‚§ facebook.com/SoftwareUniversity
ο‚§ Software University @ YouTube
ο‚§ youtube.com/SoftwareUniversity
ο‚§ Software University Forums – forum.softuni.bg

More Related Content

PPTX
06.Loops
PPTX
02. Primitive Data Types and Variables
PPTX
01. Introduction to Programming
PPTX
03. Operators Expressions and statements
PPTX
07. Arrays
PPTX
C# 101: Intro to Programming with C#
PPT
9. Input Output in java
PPTX
Java Method, Static Block
06.Loops
02. Primitive Data Types and Variables
01. Introduction to Programming
03. Operators Expressions and statements
07. Arrays
C# 101: Intro to Programming with C#
9. Input Output in java
Java Method, Static Block

What's hot (20)

PPTX
Python variables and data types.pptx
PPTX
Enumeration in c#
PPTX
Control Statements in Java
PPT
JavaScript Control Statements I
PPT
JAVA OOP
PPT
Pointers C programming
PPTX
This pointer
PPTX
java interface and packages
PPTX
String in java
PDF
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
PPTX
String Handling in c++
PDF
Methods in Java
PPTX
05. Conditional Statements
PPT
Chapter 2 Java Methods
PPT
Late and Early binding in c++
PPTX
Pointers, virtual function and polymorphism
PPTX
Java if else condition - powerpoint persentation
PDF
Introduction to python
PPT
C pointers
Python variables and data types.pptx
Enumeration in c#
Control Statements in Java
JavaScript Control Statements I
JAVA OOP
Pointers C programming
This pointer
java interface and packages
String in java
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
String Handling in c++
Methods in Java
05. Conditional Statements
Chapter 2 Java Methods
Late and Early binding in c++
Pointers, virtual function and polymorphism
Java if else condition - powerpoint persentation
Introduction to python
C pointers
Ad

Similar to 04. Console Input Output (20)

PPT
04 Console input output-
PDF
Chapter two Fundamentals of C# programming
DOCX
Write and write line methods
PPT
C# basics
PPTX
C#.net
PPT
Wlkthru vb netconsole-inputoutput
Β 
PPTX
C# overview part 1
PPTX
16 strings-and-text-processing-120712074956-phpapp02
PPTX
python-ch2.pptx
PDF
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
PPT
python fundamental for beginner course .ppt
PPT
(02) c sharp_tutorial
PPT
7512635.ppt
PPTX
13 Strings and Text Processing
PPTX
CSharp Language Overview Part 1
PPTX
lecture 2.pptx
PDF
434090527-C-Cheat-Sheet. pdf C# program
PDF
SPL 3 | Introduction to C programming
PDF
The Art of Clean Code
PDF
C# Language Overview Part I
04 Console input output-
Chapter two Fundamentals of C# programming
Write and write line methods
C# basics
C#.net
Wlkthru vb netconsole-inputoutput
Β 
C# overview part 1
16 strings-and-text-processing-120712074956-phpapp02
python-ch2.pptx
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
python fundamental for beginner course .ppt
(02) c sharp_tutorial
7512635.ppt
13 Strings and Text Processing
CSharp Language Overview Part 1
lecture 2.pptx
434090527-C-Cheat-Sheet. pdf C# program
SPL 3 | Introduction to C programming
The Art of Clean Code
C# Language Overview Part I
Ad

More from Intro C# Book (20)

PPTX
17. Java data structures trees representation and traversal
PPTX
Java Problem solving
PPTX
21. Java High Quality Programming Code
PPTX
20.5 Java polymorphism
PPTX
20.4 Java interfaces and abstraction
PPTX
20.3 Java encapsulation
PPTX
20.2 Java inheritance
PPTX
20.1 Java working with abstraction
PPTX
19. Java data structures algorithms and complexity
PPTX
18. Java associative arrays
PPTX
16. Java stacks and queues
PPTX
14. Java defining classes
PPTX
13. Java text processing
PPTX
12. Java Exceptions and error handling
PPTX
11. Java Objects and classes
PPTX
09. Java Methods
PPTX
05. Java Loops Methods and Classes
PPTX
07. Java Array, Set and Maps
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PPTX
02. Data Types and variables
17. Java data structures trees representation and traversal
Java Problem solving
21. Java High Quality Programming Code
20.5 Java polymorphism
20.4 Java interfaces and abstraction
20.3 Java encapsulation
20.2 Java inheritance
20.1 Java working with abstraction
19. Java data structures algorithms and complexity
18. Java associative arrays
16. Java stacks and queues
14. Java defining classes
13. Java text processing
12. Java Exceptions and error handling
11. Java Objects and classes
09. Java Methods
05. Java Loops Methods and Classes
07. Java Array, Set and Maps
03 and 04 .Operators, Expressions, working with the console and conditional s...
02. Data Types and variables

Recently uploaded (20)

PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
CSharp_Syntax_Basics.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxx
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
presentation_pfe-universite-molay-seltan.pptx
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PDF
Paper PDF World Game (s) Great Redesign.pdf
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
The Internet -By the Numbers, Sri Lanka Edition
Β 
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
DOCX
Unit-3 cyber security network security of internet system
PPTX
innovation process that make everything different.pptx
PPTX
PPT_M4.3_WORKING WITH SLIDES APPLIED.pptx
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
Digital Literacy And Online Safety on internet
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PPTX
Introduction to Information and Communication Technology
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PDF
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
international classification of diseases ICD-10 review PPT.pptx
CSharp_Syntax_Basics.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Module 1 - Cyber Law and Ethics 101.pptx
presentation_pfe-universite-molay-seltan.pptx
522797556-Unit-2-Temperature-measurement-1-1.pptx
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
introduction about ICD -10 & ICD-11 ppt.pptx
Paper PDF World Game (s) Great Redesign.pdf
Slides PDF The World Game (s) Eco Economic Epochs.pdf
The Internet -By the Numbers, Sri Lanka Edition
Β 
Decoding a Decade: 10 Years of Applied CTI Discipline
Unit-3 cyber security network security of internet system
innovation process that make everything different.pptx
PPT_M4.3_WORKING WITH SLIDES APPLIED.pptx
Tenda Login Guide: Access Your Router in 5 Easy Steps
Digital Literacy And Online Safety on internet
Unit-1 introduction to cyber security discuss about how to secure a system
Introduction to Information and Communication Technology
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...

04. Console Input Output

  • 1. Console Input / Output Reading and Writing to the Console Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg
  • 2. 2 1. Printing to the Console ο‚§ Printing Strings and Numbers 2. Reading from the Console ο‚§ Reading Characters ο‚§ Reading Strings ο‚§ Parsing Strings to Numeral Types ο‚§ Reading Numeral Types 3. Various Examples Table of Contents
  • 3. Printing to the Console Printing Strings, Numeral Types and Expressions
  • 4. 4 ο‚§ The console (terminal window) is used to read / display text- based information in a virtual terminal window ο‚§ Learn more from Wikipedia: terminal emulator, virtual console ο‚§ Can display different values: ο‚§ Strings ο‚§ Numeral types ο‚§ All primitive data types ο‚§ To print to the console use the Console class (System.Console) Printing to the Console
  • 5. 5 ο‚§ Provides methods for console input and output ο‚§ Input ο‚§ Read(…) – reads a single character ο‚§ ReadKey(…) – reads a combination of keys ο‚§ ReadLine(…) – reads a single line of characters ο‚§ Output ο‚§ Write(…) – prints the specified argument on the console ο‚§ WriteLine(…) – prints specified data to the console and moves to the next line The Console Class
  • 6. 6 ο‚§ Printing an integer variable: ο‚§ Printing more than one variable using a formatting string: Console.Write(…) int a = 15; Console.Write(a); // 15 double a = 15.5; int b = 14; ... Console.Write("{0} + {1} = {2}", a, b, a + b); // 15.5 + 14 = 29.5 ο‚§ The next print operation will start from the same line
  • 7. 7 Console.WriteLine(…) ο‚§ Printing more than one variable using a formatting string: string str = "Hello C#!"; Console.WriteLine(str); ο‚§ Printing a string variable + new line (rn): string name = "Marry"; int year = 1987; ... Console.WriteLine("{0} was born in {1}.", name, year); // Marry was born in 1987. ο‚§ Next printing will start from the new line
  • 8. 8 Printing to the Console – Example static void Main() { string name = "Peter"; int age = 18; string town = "Sofia"; Console.Write("{0} is {1} years old from {2}.", name, age, town); // Result: Peter is 18 years old from Sofia. Console.Write("This is on the same line!"); Console.WriteLine("Next sentence will be on a new line."); Console.WriteLine("Bye, bye, {0} from {1}.", name, town); }
  • 9. ο‚§ index ο‚§ The zero-based index of the argument whose string representation is to be included at this position in the string ο‚§ alignment ο‚§ A signed integer that indicates the total length of the field into which the argument is inserted ο‚§ a positive integer – right-aligned ο‚§ a negative integer – left-aligned Formatting Strings {index[,alignment][:formatString]}
  • 10. ο‚§ formatString ο‚§ Specifies the format of the corresponding argument's result string, e.g. "X", "C", "0.00", e.g. Formatting Strings (2) static void Main() { double pi = 1.234; Console.WriteLine("{0:0.000000}", pi); // 1.234000 } {index[,alignment][:formatString]}
  • 11. 11 Formatting Strings – Examples static void Main() { int a=2, b=3; Console.Write("{0} + {1} =", a, b); Console.WriteLine(" {0}", a+b); // 2 + 3 = 5 Console.WriteLine("{0} * {1} = {2}", a, b, a*b); // 2 * 3 = 6 float pi = 3.14159206; Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14 Console.WriteLine("Bye – Bye!"); }
  • 12. 12 Printing a Menu – Example double colaPrice = 1.20; string cola = "Coca Cola"; double fantaPrice = 1.20; string fanta = "Fanta Dizzy"; double zagorkaPrice = 1.50; string zagorka = "Zagorka"; Console.WriteLine("Menu:"); Console.WriteLine("1. {0} – {1}", cola, colaPrice); Console.WriteLine("2. {0} – {1}", fanta, fantaPrice); Console.WriteLine("3. {0} – {1}", zagorka, zagorkaPrice); Console.WriteLine("Have a nice day!");
  • 14. Reading from the Console Reading Strings and Numeral Types
  • 15. 15 ο‚§ We use the console to read information from the command line ο‚§ Usually the data is entered from the keyboard ο‚§ We can read: ο‚§ Characters ο‚§ Strings ο‚§ Numeral types (after conversion) ο‚§ To read from the console we use the methods Console.Read() and Console.ReadLine() Reading from the Console
  • 16. 16 ο‚§ Gets a single character from the console (after [Enter] is pressed) ο‚§ Returns a result of type int ο‚§ Returns -1 if there aren’t more symbols ο‚§ To get the actually read character we need to cast it to char Console.Read() int i = Console.Read(); char ch = (char) i; // Cast the int to char // Gets the code of the entered symbol Console.WriteLine("The code of '{0}' is {1}.", ch, i);
  • 17. Reading Characters from the Console Live Demo
  • 18. 18 ο‚§ Waits until a combination of keys is pressed ο‚§ Reads a single character from console or a combination of keys ο‚§ Returns a result of type ConsoleKeyInfo ο‚§ KeyChar – holds the entered character ο‚§ Modifiers – holds the state of [Ctrl], [Alt], … Console.ReadKey() ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); Console.WriteLine("Character entered: " + key.KeyChar); Console.WriteLine("Special keys: " + key.Modifiers);
  • 19. Reading Keys from the Console Live Demo
  • 20. 20 ο‚§ Gets a line of characters ο‚§ Returns a string value ο‚§ Returns null if the end of the input is reached Console.ReadLine() Console.Write("Please enter your first name: "); string firstName = Console.ReadLine(); Console.Write("Please enter your last name: "); string lastName = Console.ReadLine(); Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
  • 21. Reading Strings from the Console Live Demo
  • 22. 22 ο‚§ Numeral types can not be read directly from the console ο‚§ To read a numeral type do the following: 1. Read a string value 2. Convert (parse) it to the required numeral type ο‚§ int.Parse(string) ο‚§ Parses (converts) a string to int Reading Numeral Types string str = Console.ReadLine() int number = int.Parse(str); Console.WriteLine("You entered: {0}", number);
  • 23. 23 ο‚§ Numeral types have a method Parse(…) for extracting the numeral value from a string ο‚§ int.Parse(string) – string οƒ  int ο‚§ long.Parse(string) – string οƒ  long ο‚§ float.Parse(string) – string οƒ  float ο‚§ Causes FormatException in case of error Converting Strings to Numbers string s = "123"; int i = int.Parse(s); // i = 123 long l = long.Parse(s); // l = 123L string invalid = "xxx1845"; int value = int.Parse(invalid); // FormatException
  • 24. 24 Reading Numbers from the Console – Example static void Main() { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); Console.WriteLine("{0} + {1} = {2}", a, b, a+b); Console.WriteLine("{0} * {1} = {2}", a, b, a*b); float f = float.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f); }
  • 25. 25 ο‚§ Converting can also be done through the Convert class ο‚§ Convert.ToInt32(string[, base]) – string οƒ  int ο‚§ Convert.ToSingle(string)– string οƒ  float ο‚§ Convert.ToInt64(string)– string οƒ  long ο‚§ It uses the parse methods of the numeral types Converting Strings to Numbers (2) string s = "123"; int i = Convert.ToInt32(s); // i = 123 long l = Convert.ToInt64(s); // l = 123L string invalid = "xxx1845"; int value = Convert.ToInt32(invalid); // FormatException
  • 26. Reading Numbers from the Console Live Demo
  • 27. 27 ο‚§ Sometimes we want to handle the errors when parsing a number ο‚§ Two options: use try-catch block or TryParse() ο‚§ Parsing with TryParse(): Error Handling when Parsing string str = Console.ReadLine(); int number; if (int.TryParse(str, out number)) { Console.WriteLine("Valid number: {0}", number); } else { Console.WriteLine("Invalid number: {0}", str); }
  • 29. Regional Settings Printing and Reading Special Characters Regional Settings and the Number Formatting
  • 30. 30 ο‚§ Printing special characters on the console needs two steps: ο‚§ Change the console properties to enable Unicode-friendly font ο‚§ Enable Unicode for the Console by adjusting its output encoding ο‚§ Prefer UTF8 (Unicode) How to Print Special Characters on the Console? using System.Text; … Console.OutputEncoding = Encoding.UTF8; Console.WriteLine("Π’ΠΎΠ²Π° Π΅ ΠΊΠΈΡ€ΠΈΠ»ΠΈΡ†Π°: ☺");
  • 31. 31 ο‚§ The currency format and number formats are different in different countries ο‚§ E.g. the decimal separator could be "." or "," ο‚§ To ensure the decimal separator is "." use the following code: Decimal Separator using System.Threading; using System.Globalization; … Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Console.WriteLine(3.54); // 3.54 decimal value = decimal.Parse("1.33");
  • 33. Reading and Printing to the Console Various Examples
  • 34. 34 Printing a Letter – Example Console.Write("Enter person name: "); string person = Console.ReadLine(); Console.Write("Enter company name: "); string company = Console.ReadLine(); Console.WriteLine(" Dear {0},", person); Console.WriteLine("We are pleased to tell you that " + "{1} has accepted you to take part in the "C# Basics"" + " course. {1} wishes you a good luck!", person, company); Console.WriteLine(" Yours,"); Console.WriteLine(" {0}", company);
  • 36. 36 Calculating Area – Example Console.WriteLine("This program calculates " + "the area of a rectangle or a triangle"); Console.Write("Enter a and b (for rectangle) " + " or a and h (for triangle): "); int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); Console.Write("Enter 1 for a rectangle or 2 for a triangle: "); int choice = int.Parse(Console.ReadLine()); double area = (double) (a*b) / choice; Console.WriteLine("The area of your figure is {0}", area);
  • 38. 38 ο‚§ Basic input and output methods of the class Console ο‚§ Write(…) and WriteLine(…) ο‚§ Write values to the console ο‚§ Read(…) and ReadLine(…) ο‚§ Read values from the console ο‚§ Parsing numbers to strings ο‚§ int.Parse(…) ο‚§ double.Parse(…) ο‚§ … Summary
  • 40. License ο‚§ This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license 40 ο‚§ Attribution: this work may contain portions from ο‚§ "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license ο‚§ "C# Part I" course by Telerik Academy under CC-BY-NC-SA license
  • 41. Free Trainings @ Software University ο‚§ Software University Foundation – softuni.org ο‚§ Software University – High-Quality Education, Profession and Job for Software Developers ο‚§ softuni.bg ο‚§ Software University @ Facebook ο‚§ facebook.com/SoftwareUniversity ο‚§ Software University @ YouTube ο‚§ youtube.com/SoftwareUniversity ο‚§ Software University Forums – forum.softuni.bg

Editor's Notes