Csharp/C Sharp/Development Class/Console Input Output
Содержание
- 1 A simple command line program that reads from the console using Console.Read() and Console.ReadLine()
- 2 C# Basic Data Types
- 3 C# Hello Universe
- 4 Console command-line arguments
- 5 constructs sentences by concatenating user input until the user enters one of the termination characters
- 6 Convert input from control to upper case
- 7 Demonstrates redirecting the Console output to a file
- 8 Demonstrates some of the formatting flags for writing text to the console
- 9 Demonstrate various format specifiers
- 10 Illustrates how to read a character entered using the keyboard
- 11 Illustrates how to read a string entered using the keyboard
- 12 input a series of numbers separated by commas, parse them into integers and output the sum
- 13 Input from the console using ReadLine()
- 14 Output with parameters
- 15 Read a character from the keyboard
- 16 Read a line from console
- 17 Read a string from the keyboard, using Console.In directly
- 18 Read double and int from console
- 19 Redirect Console.Out
- 20 Terminate a control input
- 21 This program averages a list of numbers entered by the user
- 22 Use do while to read console input
- 23 Use format commands
- 24 Uses the #, 0 and comma characters to format output
- 25 Use while(true) to read console input
- 26 While loop and keyboard reading
- 27 Write to Console.Out and Console.Error
A simple command line program that reads from the console using Console.Read() and Console.ReadLine()
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
/*
read.cs. A simple command line program that reads from
the console using Console.Read() and Console.ReadLine().
Compile this program using the following line:
C:>csc read.cs
*/
using System;
public class ReadCmdLine
{
static void Main()
{
Console.WriteLine ("First, using the Read() function " +
"without clearing the buffer");
int arg;
Console.Write("Type one or more characters: ");
while ((arg = Console.Read()) > 10)
{
if (arg == 13)
Console.WriteLine (" <EOL>");
else
Console.Write (Convert.ToChar(arg));
}
Console.WriteLine();
Console.WriteLine ("Now, using the Read() function and " +
"clearing the buffer");
Console.Write("Type one or more characters: ");
arg = Console.Read ();
string str = Console.ReadLine();
Console.WriteLine ("The character is " + Convert.ToChar(arg));
}
}
C# Basic Data Types
using System;
public class BasicDataTypes
{
public static void Main(string[] args)
{
Console.WriteLine("Value is: {0}", 3);
}
}
C# Hello Universe
using System;
public class HelloDealWithCommandLineInput
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, Universe");
// iterate over command-line arguments, and print them out
for (int arg = 0; arg < args.Length; arg++)
Console.WriteLine("Arg {0}: {1}", arg, args[arg]);
}
}
Console command-line arguments
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
using System;
public class CLDemo {
public static void Main(string[] args) {
Console.WriteLine("There are " + args.Length +
" command-line arguments.");
Console.WriteLine("They are: ");
for(int i=0; i<args.Length; i++)
Console.WriteLine(args[i]);
}
}
constructs sentences by concatenating user input until the user enters one of the termination characters
using System;
public class MainClass {
public static void Main(string[] args) {
string sSentence = "";
for (; ; ) {
Console.WriteLine("Enter a string");
string sLine = Console.ReadLine();
if (IsTerminateString(sLine)) {
break;
}
sSentence = String.Concat(sSentence, sLine);
Console.WriteLine("\nYou"ve entered: {0}", sSentence);
}
}
public static bool IsTerminateString(string source) {
string[] sTerms = {"EXIT","exit","QUIT","quit"};
foreach (string sTerm in sTerms) {
if (String.rupare(source, sTerm) == 0) {
return true;
}
}
return false;
}
}
Convert input from control to upper case
using System;
public class MainClass {
static void Main() {
Console.WriteLine("Enter command:");
string resp = (Console.ReadLine()).ToLower();
switch (resp) {
case "a":
Console.WriteLine("Doing Task A");
break;
case "b":
Console.WriteLine("Doing Task B");
break;
case "c":
Console.WriteLine("Doing Task C");
break;
default:
Console.WriteLine("Bad choice");
break;
}
}
}
Demonstrates redirecting the Console output to a file
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Redirect.cs -- Demonstrates redirecting the Console output to a file
//
// Compile this program with the following command line:
// C:>csc Redirect.cs
//
using System;
using System.IO;
namespace nsStreams
{
public class Redirect
{
static public void Main ()
{
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
ostrm = new FileStream ("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter (ostrm);
}
catch (Exception e)
{
Console.WriteLine ("Cannot open Redirect.txt for writing");
Console.WriteLine (e.Message);
return;
}
Console.SetOut (writer);
Console.WriteLine ("This is a line of text");
Console.WriteLine ("Everything written to Console.Write() or");
Console.WriteLine ("Console.WriteLine() will be written to a file");
Console.SetOut (oldOut);
writer.Close();
ostrm.Close();
Console.WriteLine ("Done");
}
}
}
Demonstrates some of the formatting flags for writing text to the console
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
/*
Format.cs. Demonstrates some of the formatting flags for writing text
to the console.
Compile this program with the following command line:
C:>csc format.cs
*/
namespace nsFormat
{
using System;
public class Format
{
static readonly double e = 2.71828;
static void Main()
{
Console.WriteLine ("Integer dollar amount: {0,0:C}", 3);
Console.WriteLine ("Floating dollar amount: {0,0:C}", 3.29);
Console.WriteLine ("Integer value: {0,0:D5}", 1024);
Console.WriteLine ("Integer value: {0,0:N5}", 1024742);
Console.WriteLine ("Integer value: {0,0:N}", 1024742);
Console.WriteLine ("Integer value: {0,0:N5}", 1024742);
Console.WriteLine ("Integer value: {0,0:X}", 1024742);
Console.WriteLine ("Floating point e: {0,0:F3}", e);
Console.WriteLine ("Floating point e: {0,-8:F5}", e);
Console.WriteLine ("Floating point e: {0,-8:E2}", e);
Console.WriteLine ("Floating point e: {0,-8:E}", e);
}
}
}
Demonstrate various format specifiers
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate various format specifiers.
using System;
public class FormatDemo {
public static void Main() {
double v = 17688.65849;
double v2 = 0.15;
int x = 21;
Console.WriteLine("{0:F2}", v);
Console.WriteLine("{0:N5}", v);
Console.WriteLine("{0:e}", v);
Console.WriteLine("{0:r}", v);
Console.WriteLine("{0:p}", v2);
Console.WriteLine("{0:X}", x);
Console.WriteLine("{0:D12}", x);
Console.WriteLine("{0:C}", 189.99);
}
}
Illustrates how to read a character entered using the keyboard
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example2_13.cs illustrates how to read
a character entered using the keyboard
*/
public class Example2_131
{
public static void Main()
{
System.Console.Write("Enter a character: ");
char myChar = (char) System.Console.Read();
System.Console.WriteLine("You entered " + myChar);
}
}
Illustrates how to read a string entered using the keyboard
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example2_14.cs illustrates how to
read a string entered using the keyboard
*/
public class Example2_141
{
public static void Main()
{
System.Console.Write("Enter a string: ");
string myString = System.Console.ReadLine();
System.Console.WriteLine("You entered " + myString);
}
}
input a series of numbers separated by commas, parse them into integers and output the sum
using System;
class Class1 {
public static void Main(string[] args) {
Console.WriteLine("Input a series of numbers separated by commas:");
string input = Console.ReadLine();
char[] cDividers = { ",", " " };
string[] segments = input.Split(cDividers);
int nSum = 0;
foreach (string s in segments) {
if (s.Length > 0) {
if (IsAllDigits(s)) {
int num = Int32.Parse(s);
Console.WriteLine("Next number = {0}", num);
nSum += num;
}
}
}
Console.WriteLine("Sum = {0}", nSum);
}
public static bool IsAllDigits(string sRaw) {
string s = sRaw.Trim();
if (s.Length == 0) {
return false;
}
for (int index = 0; index < s.Length; index++) {
if (Char.IsDigit(s[index]) == false) {
return false;
}
}
return true;
}
}
Input from the console using ReadLine()
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Input from the console using ReadLine().
using System;
public class ReadString {
public static void Main() {
string str;
Console.WriteLine("Enter some characters.");
str = Console.ReadLine();
Console.WriteLine("You entered: " + str);
}
}
Output with parameters
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
public class AssignedValues {
static void Main( )
{
int myInt;
//other code here...
myInt = 7; // assign to it
System.Console.WriteLine("Assigned, myInt: {0}", myInt);
myInt = 5;
System.Console.WriteLine("Reassigned, myInt: {0}", myInt);
}
}
Read a character from the keyboard
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Read a character from the keyboard.
using System;
public class KbIn {
public static void Main() {
char ch;
Console.Write("Press a key followed by ENTER: ");
ch = (char) Console.Read(); // get a char
Console.WriteLine("Your key is: " + ch);
}
}
Read a line from console
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// dbTest.cs -- Sample program to be used with cordbg.exe
//
// Compile this program with the following command line:
// C:>csc /debug:full dbTest.cs
//
using System;
namespace nsDebug
{
public class dbTest
{
static public void Main ()
{
double x = 7.0;
while (true)
{
Console.Write ("\r\nPlease enter a number: ");
string str = Console.ReadLine ();
if (str.Length == 0)
break;
double val = 0;
try
{
val = Convert.ToDouble (str);
}
catch (Exception)
{
Console.WriteLine ("\r\nInvalid number");
continue;
}
Console.WriteLine (x + " X " + val + " = {0,0:F6}", val / x);
}
}
}
}
Read a string from the keyboard, using Console.In directly
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Read a string from the keyboard, using Console.In directly.
using System;
public class ReadChars2 {
public static void Main() {
string str;
Console.WriteLine("Enter some characters.");
str = Console.In.ReadLine();
Console.WriteLine("You entered: " + str);
}
}
Read double and int from console
using System;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
(new Program()).run();
}
public void run() {
double dailyRate = readDouble("Enter your daily rate: ");
int noOfDays = readInt("Enter the number of days: ");
writeFee(calculateFee(dailyRate, noOfDays));
}
private void writeFee(double p) {
Console.WriteLine("The consultant"s fee is: {0}", p * 1.1);
}
private double calculateFee(double dailyRate, int noOfDays) {
return dailyRate * noOfDays;
}
private int readInt(string p) {
Console.Write(p);
string line = Console.ReadLine();
return int.Parse(line);
}
private double readDouble(string p) {
Console.Write(p);
string line = Console.ReadLine();
return double.Parse(line);
}
}
Redirect Console.Out
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Redirect Console.Out.
using System;
using System.IO;
public class Redirect {
public static void Main() {
StreamWriter log_out;
try {
log_out = new StreamWriter("logfile.txt");
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "Cannot open file.");
return ;
}
// Direct standard output to the log file.
Console.SetOut(log_out);
Console.WriteLine("This is the start of the log file.");
for(int i=0; i<10; i++) Console.WriteLine(i);
Console.WriteLine("This is the end of the log file.");
log_out.Close();
}
}
Terminate a control input
using System;
public class MainClass {
static void Main() {
string resp;
Console.WriteLine("Enter command ("x" to end):");
while ((resp = (Console.ReadLine()).ToLower()) != "x") {
switch (resp) {
case "a":
Console.WriteLine("Doing Task A");
break;
case "b":
Console.WriteLine("Doing Task B");
break;
default:
Console.WriteLine("Bad choice");
break;
}
}
}
}
This program averages a list of numbers entered by the user
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// This program averages a list of numbers entered by the user.
using System;
using System.IO;
public class AvgNums {
public static void Main() {
string str;
int n;
double sum = 0.0;
double avg, t;
Console.Write("How many numbers will you enter: ");
str = Console.ReadLine();
try {
n = Int32.Parse(str);
}
catch(FormatException exc) {
Console.WriteLine(exc.Message);
n = 0;
}
catch(OverflowException exc) {
Console.WriteLine(exc.Message);
n = 0;
}
Console.WriteLine("Enter " + n + " values.");
for(int i=0; i < n ; i++) {
Console.Write(": ");
str = Console.ReadLine();
try {
t = Double.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
t = 0.0;
}
catch(OverflowException exc) {
Console.WriteLine(exc.Message);
t = 0;
}
sum += t;
}
avg = sum / n;
Console.WriteLine("Average is " + avg);
}
}
Use do while to read console input
using System;
public class MainClass {
static void Main() {
string resp;
do {
Console.WriteLine("Menu\n\n1 - Task A");
Console.WriteLine("2 - Task B");
Console.WriteLine("E - E(xit)");
resp = (Console.ReadLine()).ToLower();
}
while (resp != "e");
}
}
Use format commands
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use format commands.
using System;
public class DisplayOptions {
public static void Main() {
int i;
Console.WriteLine("Value\tSquared\tCubed");
for(i = 1; i < 10; i++)
Console.WriteLine("{0}\t{1}\t{2}",
i, i*i, i*i*i);
}
}
Uses the #, 0 and comma characters to format output
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
/*
Picture.cs. Uses the #, 0 and comma characters to format output
*/
using System;
public class Picture
{
static void Main()
{
Console.WriteLine ("Using the # character");
Console.WriteLine ("\tInteger dollar amount: {0,0:$###.##}", 3);
Console.WriteLine ("\tFloating dollar amount: {0,0:$###.##}", 3.29);
Console.WriteLine ("\tInteger value: {0,0:###,###}",1428);
Console.WriteLine ("\tFloating point value: {0,0:#,###.#####}", 1428.571);
Console.WriteLine ("Using the $ character");
Console.WriteLine ("\tInteger dollar amount: {0,0:$000.00}", 3);
Console.WriteLine ("\tFloating dollar amount: {0,0:$000.00}", 3.29);
Console.WriteLine ("Using the comma alone");
Console.WriteLine ("\tInteger value: {0,0:000,000}", 1428);
Console.WriteLine ("\tFloating point value: {0,0:0,000.000}", 1428.571);
}
}
Use while(true) to read console input
using System;
public class MainClass {
static void Main() {
string resp;
while (true) {
Console.WriteLine("Menu\n\n1 - Task A");
Console.WriteLine("2 - Task B");
Console.WriteLine("E - E(xit)");
resp = (Console.ReadLine()).ToLower();
if (resp == "e") {
break;
}
}
}
}
While loop and keyboard reading
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
namespace nsLoops
{
using System;
public class Loops
{
static public void Main ()
{
int [] arr = new int [5];
for (int x = 0; x < arr.Length; ++x)
{
bool done = false;
while (!done)
{
Console.Write ("Enter a value for element {0}: ", x);
string str = Console.ReadLine ();
int val;
try
{
val = int.Parse (str);
}
catch (FormatException)
{
Console.WriteLine ("Please enter an integer value\r\n");
continue;
}
arr[x] = val;
done = true;
}
}
int index = 0;
foreach (int val in arr)
{
Console.WriteLine ("arr[{0}] = {1}", index, val);
++index;
}
}
}
}
Write to Console.Out and Console.Error
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Write to Console.Out and Console.Error.
using System;
public class ErrOut {
public static void Main() {
int a=10, b=0;
int result;
Console.Out.WriteLine("This will generate an exception.");
try {
result = a / b; // generate an exception
} catch(DivideByZeroException exc) {
Console.Error.WriteLine(exc.Message);
}
}
}