Bài tập nhập vào kí tự bằng console.read năm 2024

Ở bài hôm trước, mình có nói cách ghi dữ liệu vào file Text trong Visual C# - cho dự án lưu log. Vậy đã ghi rồi, làm thế nào để đọc??? Bài hôm nay, mình sẽ hướng dẫn cách đọc dữ liệu từ file Text thông qua Visual C# nhé!!!

II. Lớp StreamReader trong C#

Tương tự như bài trước, để viết dữ liệu vô Text dùng lớp StreamWriter thì ở đây ta dùng StreamReader để đọc dữ liệu trong C#. Lớp StreamReader kế thừa từ lớp abstract cơ sở là TextReader mà biểu diễn một reader để đọc một dãy ký tự. Bảng sau miêu tả một số phương thức được sử dụng phổ biến của lớp StreamReader trong C#:

1 public override void Close()

Nó đóng đối tượng StreamReader và Underlying Stream, và giải phóng bất kỳ nguồn hệ thống nào được liên kết với Reader đó

2 public override int Peek()

Trả về ký tự có sẵn tiếp theo nhưng không hủy nó

3 public override int Read()

Đọc ký tự tiếp theo từ Input Stream và tăng vị trí ký tự thêm 1

Để có danh sách đầy đủ các phương thức trong lớp StreamWriter, bạn tham khảo Microsoft Documentation về C#.

III. Tiến hành thôi

Ở bài này, mình cũng làm việc với Console Application...Đã thực hiện Console Application thì Winform quá đơn giản rồi, hihe.

Để đọc dữ liệu ta có 2 cách:

C1: Sử dụng StreamReader

FileStream fs = new FileStream(filepath, FileMode.Open); StreamReader rd = new StreamReader(fs, Encoding.Unicode);

C2: đọc trực tiếp sử dụng lớp File

string[] lines = File.ReadAllLines(filepath);

Code mẫu:

C1:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;//Sử dụng thư viện này để làm việc với Stream namespace ReadText {

class Program
{
    static void Main(string[] args)
    {
        FileStream fs = new FileStream("E:\\test.txt", FileMode.Open);
        StreamReader rd = new StreamReader(fs, Encoding.UTF8);
        String giatri = rd.ReadToEnd();// ReadLine() chỉ đọc 1 dòng đầu thoy, ReadToEnd là đọc hết
        Console.WriteLine(giatri);
        rd.Close();
        Console.ReadLine();
    }
}
}

C2:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;//Sử dụng thư viện này để làm việc với Stream namespace ReadText {

class Program
{
    static void Main(string[] args)
    {
        string[] lines = File.ReadAllLines(@"E:\test.txt");
        foreach (string s in lines)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}
}

Thành quả:

IV. Lời kết

Như vậy, với bài này, các bạn có thể đọc các dữ liệu trong Text phục vụ các dự án ghi log với Arduino. Chúc các bạn thành công!!!

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Console.Read Method

  • Reference

Definition

Reads the next character from the standard input stream.

public:
 static int Read();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static int Read ();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
public static int Read ();
public static int Read ();
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member Read : unit -> int
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
static member Read : unit -> int
static member Read : unit -> int
Public Shared Function Read () As Integer

Returns

The next character from the input stream, or negative one (-1) if there are currently no more characters to be read.

Attributes

Exceptions

Examples

The following example demonstrates the Read method.

// This example demonstrates the Console.Read() method. using namespace System; int main() { String^ m1 = "\nType a string of text then press Enter. " "Type '+' anywhere in the text to quit:\n"; String^ m2 = "Character '{0}' is hexadecimal 0x{1:x4}."; String^ m3 = "Character is hexadecimal 0x{0:x4}."; Char ch; int x; // Console::WriteLine( m1 ); do {

  x = Console::Read();
  try
  {
     ch = Convert::ToChar( x );
     if ( Char::IsWhiteSpace( ch ) )
     {
        Console::WriteLine( m3, x );
        if ( ch == 0x0a )
                    Console::WriteLine( m1 );
     }
     else
              Console::WriteLine( m2, ch, x );
  }
  catch ( OverflowException^ e ) 
  {
     Console::WriteLine( "{0} Value read = {1}.", e->Message, x );
     ch = Char::MinValue;
     Console::WriteLine( m1 );
  }
} while ( ch != '+' ); } / This example produces the following results: Type a string of text then press Enter. Type '+' anywhere in the text to quit: The quick brown fox. Character 'T' is hexadecimal 0x0054. Character 'h' is hexadecimal 0x0068. Character 'e' is hexadecimal 0x0065. Character is hexadecimal 0x0020. Character 'q' is hexadecimal 0x0071. Character 'u' is hexadecimal 0x0075. Character 'i' is hexadecimal 0x0069. Character 'c' is hexadecimal 0x0063. Character 'k' is hexadecimal 0x006b. Character is hexadecimal 0x0020. Character 'b' is hexadecimal 0x0062. Character 'r' is hexadecimal 0x0072. Character 'o' is hexadecimal 0x006f. Character 'w' is hexadecimal 0x0077. Character 'n' is hexadecimal 0x006e. Character is hexadecimal 0x0020. Character 'f' is hexadecimal 0x0066. Character 'o' is hexadecimal 0x006f. Character 'x' is hexadecimal 0x0078. Character '.' is hexadecimal 0x002e. Character is hexadecimal 0x000d. Character is hexadecimal 0x000a. Type a string of text then press Enter. Type '+' anywhere in the text to quit: ^Z Value was either too large or too small for a character. Value read = -1. Type a string of text then press Enter. Type '+' anywhere in the text to quit: + Character '+' is hexadecimal 0x002b. /

// This example demonstrates the Console.Read() method. using System; class Sample {

public static void Main()
{
string m1 = "\nType a string of text then press Enter. " +
            "Type '+' anywhere in the text to quit:\n";
string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
string m3 = "Character     is hexadecimal 0x{0:x4}.";
char ch;
int x;
//
Console.WriteLine(m1);
do
    {
    x = Console.Read();
    try
        {
        ch = Convert.ToChar(x);
        if (Char.IsWhiteSpace(ch))
           {
           Console.WriteLine(m3, x);
           if (ch == 0x0a)
               Console.WriteLine(m1);
           }
        else
            {
                Console.WriteLine(m2, ch, x);
            }
        }
    catch (OverflowException e)
        {
        Console.WriteLine("{0} Value read = {1}.", e.Message, x);
        ch = Char.MinValue;
        Console.WriteLine(m1);
        }
    } while (ch != '+');
}
} / This example produces the following results: Type a string of text then press Enter. Type '+' anywhere in the text to quit: The quick brown fox. Character 'T' is hexadecimal 0x0054. Character 'h' is hexadecimal 0x0068. Character 'e' is hexadecimal 0x0065. Character is hexadecimal 0x0020. Character 'q' is hexadecimal 0x0071. Character 'u' is hexadecimal 0x0075. Character 'i' is hexadecimal 0x0069. Character 'c' is hexadecimal 0x0063. Character 'k' is hexadecimal 0x006b. Character is hexadecimal 0x0020. Character 'b' is hexadecimal 0x0062. Character 'r' is hexadecimal 0x0072. Character 'o' is hexadecimal 0x006f. Character 'w' is hexadecimal 0x0077. Character 'n' is hexadecimal 0x006e. Character is hexadecimal 0x0020. Character 'f' is hexadecimal 0x0066. Character 'o' is hexadecimal 0x006f. Character 'x' is hexadecimal 0x0078. Character '.' is hexadecimal 0x002e. Character is hexadecimal 0x000d. Character is hexadecimal 0x000a. Type a string of text then press Enter. Type '+' anywhere in the text to quit: ^Z Value was either too large or too small for a character. Value read = -1. Type a string of text then press Enter. Type '+' anywhere in the text to quit: + Character '+' is hexadecimal 0x002b. /
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static int Read ();

0

[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static int Read ();

1

Remarks

The Read method blocks its return while you type input characters; it terminates when you press the key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Subsequent calls to the Read method retrieve your input one character at a time. After the final character is retrieved, Read blocks its return again and the cycle repeats.

Note that the method does not return -1 unless you perform one of the following actions:

  • Simultaneously press the modifier key and console key (Ctrl+Z), which signals the end-of-file condition. If you're on Windows, you must also press the console key.
  • Press an equivalent key that signals the end-of-file condition, such as the F6 function key in Windows.
  • Redirect the input stream to a source, such as a text file, that has an actual end-of-file character.

Applies to

See also

Collaborate with us on GitHub

The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.