본문 바로가기
C++ 200제/코딩 IT 정보

C# Console.ReadLine 함수 사용법 (콘솔에서 문자열 처리)

by vicddory 2017. 6. 23.

C# Console.ReadLine 함수 사용법 (콘솔에서 문자열 처리)


Console.ReadLine은 콘솔창에서 입력받는데, 사용자가 엔터를 누르면 문자열을 반환하고 다음 작업을 결정합니다.


사용 예. 개발 과정에선 입력 과정을 반복하는 것이 좋습니다. 아래 예제는 While(true) 무한 반복 루프를 통해 Console.ReadLine() 함수 사용 방법을 나타냅니다. (입력받은 문자열의 길이를 리턴하는 소스)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
 
class Program
{
    static void Main()
    {
        while (true// Loop indefinitely
        {
            Console.WriteLine("Enter input:"); // Prompt
            string line = Console.ReadLine(); // Get string from user
 
            if (line == "exit"// Check string
            {
                break;
            }
 
            Console.Write("You typed "); // Report output
            Console.Write(line.Length);
            Console.WriteLine(" character(s)");
        }
    }
}
cs


Console.ReadLine 예제[C# 콘솔 키 입력] Readline Key


Main 함수는 콘솔창에 결과(문자열 길이)를 표시하는 무한 루프입니다. 사용자가 "exit"를 누르면 종료되지만, 그전엔 계속 사용자 입력을 받습니다.


두 번째 예제. Console.ReadLine() 함수로 받은 문자열을 정수로 변환합니다. int.TryParse() 함수를 호출하여 정수 여부를 확인한 뒤 결과를 콘솔에 나타냅니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
 
class Program
{
    static void Main()
    {
        Console.WriteLine("Type an integer:");
        string line = Console.ReadLine(); // Read string from console
        int value;
 
        if (int.TryParse(line, out value)) // Try to parse the string as an integer
        {
            Console.Write("Multiply integer by 10: ");
            Console.WriteLine(value * 10); // Multiply the integer and display it
        }
        else
        {
            Console.WriteLine("Not an integer!");
        }
    }
}
cs


int.TryParse 함수 예제[C# 콘솔 키 입력] Readline Key


프로그램은 사용자에게 입력을 요구합니다. 한 줄의 문자열은 Console.ReadLine() 함수를 통해 문자열 데이터로 전해지고 코딩 내용에 따라 콘솔 창에 결과가 나타납니다.


C# Console.ReadLine 함수 사용법 (콘솔에서 문자열 처리)

댓글