C# 기초: 입출력(Essential Input/Output) 완벽 가이드
C# 기초: 입출력 필수 가이드
이 가이드는 C#의 핵심 입출력 기법을 다루며, 사용자 입력 읽기와 결과 출력을 신뢰성 있게 수행하는 방법을 보여줍니다.
C# 출력(Output)
콘솔에 데이터를 출력하는 두 가지 주요 메서드:
System.Console.WriteLine()
System.Console.Write()
System은 네임스페이스, Console은 클래스, WriteLine과 Write는 메서드입니다.
예제 1: WriteLine()으로 문자열 출력
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
Console.WriteLine("C# is cool");
}
}
}
실행 결과:
C# is cool
WriteLine() vs Write() 차이
WriteLine()은 텍스트 출력 후 줄바꿈을 수행하지만, Write()는 줄바꿈 없이 출력합니다.
예제 2: WriteLine()과 Write() 사용
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
Console.WriteLine("Prints on ");
Console.WriteLine("New line");
Console.Write("Prints on ");
Console.Write("Same line");
}
}
}
출력:
Prints on
New line
Prints on Same line
변수와 리터럴 출력
두 메서드 모두 변수와 리터럴을 출력할 수 있습니다.
예제 3: 변수와 리터럴 출력
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
int value = 10; // 변수
Console.WriteLine(value);
Console.WriteLine(50.05); // 리터럴
}
}
}
결과:
10
50.05
+ 연산자로 문자열 연결
출력 시 + 연산자로 문자열을 결합할 수 있습니다.
예제 4: 연결 출력
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
int val = 55;
Console.WriteLine("Hello " + "World");
Console.WriteLine("Value = " + val);
}
}
}
결과:
Hello World
Value = 55
서식 문자열 – 더 깔끔한 방법
서식 문자열은 플레이스홀더를 런타임에 치환하여 가독성을 높이고 오류를 줄입니다.
대신:
Console.WriteLine("Value = " + val);
다음처럼 사용:
Console.WriteLine("Value = {0}", val);
{0}은 val의 자리표시자입니다. 여러 변수는 추가 플레이스홀더로 처리.
예제 5: 문자열 서식 사용
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
int firstNumber = 5, secondNumber = 10, result;
result = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result);
}
}
}
출력:
5 + 10 = 15
이 방식이 수동 연결보다 읽기 쉽고 오류가 적습니다.
C# 입력(Input)
사용자 입력을 받는 가장 간단한 방법은 Console.ReadLine()입니다. 더 세밀한 입력을 위해 Read()와 ReadKey()도 있습니다.
예제 6: 사용자 문자열 입력 받기
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
}
}
}
출력:
Enter a string - Hello World
You entered 'Hello World'
ReadLine(), Read(), ReadKey() 이해하기
- ReadLine(): 입력 스트림에서 한 줄 전체를 읽어 문자열로 반환.
- Read(): 다음 문자를 읽어 ASCII 값(정수) 반환.
- ReadKey(): Enter 키 없이 키 입력을 즉시 감지; 일시 정지 프롬프트 등에 유용.
예제 7: Read()와 ReadKey() 시연
using System;
namespace Sample {
class Test {
public static void Main(string[] args) {
int userInput;
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Console.WriteLine();
Console.Write("Input using Read() - ");
userInput = Console.Read();
Console.WriteLine("Ascii Value = {0}", userInput);
}
}
}
출력:
Press any key to continue...
x
Input using Read() - Learning C#
Ascii Value = 76
ReadKey()는 키를 즉시 표시하지만, Read()는 한 줄을 읽고 첫 문자의 ASCII 코드만 반환합니다(여기서 'L'의 76).
숫자 값 읽기
문자열은 직접 읽지만, 숫자 타입은 변환이 필요합니다. Convert 클래스가 간편한 메서드를 제공합니다.
예제 8: 사용자 입력을 숫자로 변환
using System;
namespace UserInput {
class MyClass {
public static void Main(string[] args) {
string userInput;
int intVal;
double doubleVal;
Console.Write("Enter integer value: ");
userInput = Console.ReadLine();
intVal = Convert.ToInt32(userInput);
Console.WriteLine("You entered {0}", intVal);
Console.Write("Enter double value: ");
userInput = Console.ReadLine();
doubleVal = Convert.ToDouble(userInput);
Console.WriteLine("You entered {0}", doubleVal);
}
}
}
결과:
Enter integer value: 101
You entered 101
Enter double value: 59.412
You entered 59.412
Convert.ToInt32()와 ToDouble()이 입력 문자열을 원하는 숫자 타입으로 변환합니다. 전체 변환 메서드는 .NET 문서 참조.