
C# print 문: 기초 배우기
인쇄는 응용 프로그램 개발의 기본적인 측면으로, 개발자가 사용자와 콘솔이나 실제 문서를 통해 소통하도록 합니다. C#에서 print 구문은 정보를 표시하는 다재다능한 도구이며, 이 기사에서는 그 사용법, 옵션 및 모범 사례를 탐구할 것입니다.
C# 인쇄 구문 소개
C#에서 print 문장은 콘솔에 정보를 출력하는 데 사용됩니다. 프로그램과 사용자 간의 통신을 용이하게 하며, 메시지, 데이터 또는 작업 결과를 표시할 방법을 제공합니다. 이 구문은 디버깅, 사용자 상호작용 및 프로그램 실행 중 일반 정보 출력에 필수적입니다.
기본 구문
C#에서 print 문장의 기본 구문은 지정된 문자열이나 값 뒤에 자동으로 새 줄을 추가하는 Console.WriteLine 메서드를 사용하는 것입니다. System 네임스페이스 내에 자리 잡고 있는 Console 클래스는 표준 출력 스트림에 정보를 출력하는 데 사용되는 WriteLine 메소드를 포함합니다. 이 메소드는 표준 입력 스트림을 통해 획득한 사용자 입력과 다수의 변수를 갖는 문자열 라인으로 동작합니다.
다음은 간단한 예입니다.
using System;
class Program
{
public static void Main()
{
// Print a greeting message to the console
Console.WriteLine("Hello, C# Print Statement!");
}
}Imports System
Friend Class Program
Public Shared Sub Main()
' Print a greeting message to the console
Console.WriteLine("Hello, C# Print Statement!")
End Sub
End Class이 간단한 예제에서는 Console 클래스의 WriteLine 메서드를 사용하여 지정된 문자열을 콘솔에 인쇄한 후 새 줄을 추가합니다.
변수와 값 인쇄
Console.WriteLine 메서드의 매개 변수로 포함하여 변수의 문자열 리터럴 및 숫자 값을 인쇄할 수 있습니다. 예를 들어:
using System;
class Program
{
public static void Main()
{
// Define a string message and an integer number
string message = "Welcome to C#";
int number = 42;
// Print the message and number to the console
Console.WriteLine(message);
Console.WriteLine("The answer is: " + number);
}
}Imports System
Module Program
Public Sub Main()
' Define a string message and an integer number
Dim message As String = "Welcome to C#"
Dim number As Integer = 42
' Print the message and number to the console
Console.WriteLine(message)
Console.WriteLine("The answer is: " & number)
End Sub
End Module위의 코드 예제는 message 및 number 변수의 값이 WriteLine 메서드를 사용하여 콘솔에 출력되는 방법을 보여줍니다.

특수 문자와 문자열 포맷
C#은 플레이스홀더 또는 문자열 보간법을 사용하여 출력을 형식화할 수 있는 다양한 방법을 제공합니다. 다음 예제를 확인하십시오:
using System;
class Program
{
public static void Main()
{
// Initialize variables
string name = "John";
int age = 30;
// Use placeholders for string formatting
Console.WriteLine("Name: {0}, Age: {1}", name, age);
// Use string interpolation for a cleaner approach
Console.WriteLine($"Name: {name}, Age: {age}");
}
}Imports System
Friend Class Program
Public Shared Sub Main()
' Initialize variables
Dim name As String = "John"
Dim age As Integer = 30
' Use placeholders for string formatting
Console.WriteLine("Name: {0}, Age: {1}", name, age)
' Use string interpolation for a cleaner approach
Console.WriteLine($"Name: {name}, Age: {age}")
End Sub
End Class두 가지 접근 방식은 동일한 결과를 달성하며, 포맷된 문자열에 변수 값을 삽입할 수 있게 합니다.
추가 포맷 옵션
줄 종결자
기본적으로 줄 종결자는 "\r\n" (캐리지 리턴 + 라인 피드)입니다. 이를 다음을 사용하여 변경할 수 있습니다:
Console.Out.NewLine = "\n";
// Set to newline character onlyImports Microsoft.VisualBasic
Console.Out.NewLine = vbLf
' Set to newline character only포맷 사용자 지정
포맷 문자열은 플레이스홀더와 포맷 옵션을 사용하여 사용자 지정을 허용합니다. 예를 들어:
using System;
class Program
{
public static void Main()
{
// Get the current date
DateTime currentDate = DateTime.Now;
// Print the current date in a long date pattern
Console.WriteLine("Today is {0:D}", currentDate);
}
}Imports System
Friend Class Program
Public Shared Sub Main()
' Get the current date
Dim currentDate As DateTime = DateTime.Now
' Print the current date in a long date pattern
Console.WriteLine("Today is {0:D}", currentDate)
End Sub
End Class복합 포맷
다음은 복합 포맷 및 문자 배열을 한 줄로 인쇄하는 예제입니다:
using System;
class Program
{
public static void Main()
{
// Define a price and character array
double price = 19.99;
char[] chars = { 'A', 'B', 'C' };
// Format the output string using placeholders
Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}",
"Widget", price, new string(chars));
}
}Imports System
Friend Class Program
Public Shared Sub Main()
' Define a price and character array
Dim price As Double = 19.99
Dim chars() As Char = { "A"c, "B"c, "C"c }
' Format the output string using placeholders
Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, New String(chars))
End Sub
End Class이 코드 예제에서 제품 이름과 가격은 복합 형식을 사용하여 포맷되며, new string(chars)을 사용하여 문자열로 인쇄됩니다.
새 줄 및 줄 바꿈
출력 구조화에 있어서 새 줄 및 줄 바꿈을 제어하는 것은 중요합니다. Console.WriteLine 메서드는 자동으로 새 줄을 추가하지만, Console.Write 메서드를 사용하여 같은 줄에 인쇄할 수 있습니다. 다음 예제를 참조하세요:
using System;
class Program
{
public static void Main()
{
// Print parts of a sentence on the same line
Console.Write("This ");
Console.Write("is ");
Console.Write("on ");
Console.WriteLine("the same line.");
}
}Imports System
Friend Class Program
Public Shared Sub Main()
' Print parts of a sentence on the same line
Console.Write("This ")
Console.Write("is ")
Console.Write("on ")
Console.WriteLine("the same line.")
End Sub
End Class위의 코드 예제는 출력을 다음과 같이 생성합니다: "이것은 같은 줄에 있습니다."
IronPrint: .NET 용 올인원 프린트 라이브러리
IronPrint는 Iron Software에서 개발한 .NET 개발자들이 물리 문서를 인쇄할 수 있도록 설계된 포괄적인 인쇄 라이브러리입니다. 이 라이브러리는 다양한 기능을 제공하고 여러 환경을 지원하여 C# 애플리케이션에서 문서를 인쇄하기 위한 다목적 솔루션을 제공합니다. 만약 물리적 프린터가 사용 가능하지 않다면, 문서를 인쇄할 때 기본 프린터를 기본 값으로 사용합니다.

설치
IronPrint는 NuGet 패키지 관리자 콘솔이나 Visual Studio 패키지 관리자를 통해 설치할 수 있습니다.
NuGet 패키지 관리자 콘솔을 사용하여 IronPrint를 설치하려면 다음 명령어를 사용하십시오:
또한, Visual Studio를 사용하여 프로젝트에 설치할 수 있습니다. 솔루션 익스플로러를 마우스 오른쪽 버튼으로 클릭하고 솔루션용 NuGet 패키지 관리자를 관리 클릭하십시오. NuGet 검색 탭에서 IronPrint를 검색한 후 설치를 클릭하여 프로젝트에 추가합니다:

왜 IronPrint를 고려해야 할까요?
1. 크로스 플랫폼 마법
Windows, macOS, iOS 또는 Android 중 어떤 것을 사용하든지 IronPrint는 당신을 지원합니다. 이 라이브러리는 .NET 버전 8, 7, 6, 5 및 Core 3.1+와 잘 작동하여 매우 다재다능합니다.
2. 형식 유연성
PDF, PNG, HTML, TIFF, GIF, JPEG, IMAGE 및 BITMAP 등 모든 것을 IronPrint가 처리합니다.
3. 인쇄 설정
DPI, 복사본 수, 종이 방향 등 인쇄 설정의 사용자 정의를 허용합니다.
4. 쉬운 설치
IronPrint 설치는 매우 간단합니다. NuGet 패키지 관리자 콘솔을 사용하여 명령어 Install-Package IronPrint을 입력하기만 하면 됩니다.
어떻게 작동합니까?
인쇄는 IronPrint와 함께라면 매우 간단합니다. dialog와 함께 쉽게 인쇄하고 출력 설정을 제어할 수 있는 빠른 코드 예제를 확인하세요:
using IronPrint;
class PrintExample
{
public static void Main()
{
// Print a document
Printer.Print("newDoc.pdf");
// Show a print dialog for user interaction
Printer.ShowPrintDialog("newDoc.pdf");
// Customize print settings
PrintSettings printSettings = new PrintSettings
{
Dpi = 150,
NumberOfCopies = 2,
PaperOrientation = PaperOrientation.Portrait
};
// Print using the customized settings
Printer.Print("newDoc.pdf", printSettings);
}
}Imports IronPrint
Friend Class PrintExample
Public Shared Sub Main()
' Print a document
Printer.Print("newDoc.pdf")
' Show a print dialog for user interaction
Printer.ShowPrintDialog("newDoc.pdf")
' Customize print settings
Dim printSettings As New PrintSettings With {
.Dpi = 150,
.NumberOfCopies = 2,
.PaperOrientation = PaperOrientation.Portrait
}
' Print using the customized settings
Printer.Print("newDoc.pdf", printSettings)
End Sub
End ClassIronPrint 및 인쇄 허브로서의 기능에 대한 더 자세한 정보는 문서 페이지를 방문하십시오.
결론
C#에서의 print 문장은 사용자와 소통하고, 정보를 표시하며, 코드를 디버깅하는 데 강력한 도구입니다. 초보자든 경력자든 간에 Console.WriteLine 메서드를 효과적으로 사용하는 방법을 이해하는 것은 정보성 있고 사용자 친화적인 애플리케이션을 만드는 데 필수적입니다.
IronPrint는 정확성, 사용 용이성, 속도를 원하시는 분들께 적합한 인쇄 라이브러리입니다. 웹앱, MAUI, Avalonia 또는 .NET 관련 작업을 하든지 IronPrint가 당신을 지원합니다.
IronPrint는 유료 라이브러리이지만, 무료 체험판을 제공합니다.
개발자로서의 삶을 좀 더 쉽게 만들 준비가 되셨나요? IronPrint를 여기에서 받으세요!

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.
관련 기사


