programming language/C++

C++ 입출력

metamong-data 2025. 1. 13. 14:19
728x90
반응형

개요

C++에서 입출력(Input/Output, I/O)은 사용자와 프로그램 간 데이터를 주고받는 중요한 기능입니다. 표준 입출력 라이브러리를 통해 간단하게 입력을 받고 출력할 수 있습니다. 이 문서에서는 주요 입출력 기능과 사용법을 설명합니다.

기본 입출력

1. 표준 출력 (Standard Output)

특징

  1. cout 객체를 사용하여 데이터를 출력합니다.

  2. << 연산자를 사용하여 출력 내용을 지정합니다.

예제

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    cout << "The value of pi is approximately " << 3.14 << endl;
    return 0;
}

출력

Hello, World!
The value of pi is approximately 3.14

2. 표준 입력 (Standard Input)

특징

  1. cin 객체를 사용하여 데이터를 입력받습니다.

  2. >> 연산자를 사용하여 변수를 입력받습니다.

  3. 입력은 공백, 탭, 또는 줄바꿈으로 구분됩니다.

예제

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "You are " << age << " years old." << endl;
    return 0;
}

출력

Enter your age: 25
You are 25 years old.

3. 복수 입력 및 출력

특징

  1. cincout을 조합하여 여러 값을 처리할 수 있습니다.

  2. 여러 변수를 한 번에 입력받거나 출력할 수 있습니다.

예제

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;
    cout << "Sum: " << (a + b) << endl;
    cout << "Product: " << (a * b) << endl;
    return 0;
}

출력

Enter two numbers: 3 5
Sum: 8
Product: 15

고급 입출력

1. 파일 입출력 (File I/O)

특징

  1. 파일을 열고 읽거나 쓰는 데 fstream, ifstream, ofstream 헤더를 사용합니다.

  2. 파일 열기, 쓰기, 읽기, 닫기와 같은 작업을 수행할 수 있습니다.

예제: 파일 쓰기

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream outFile("example.txt");
    if (outFile.is_open()) {
        outFile << "This is a line in the file." << endl;
        outFile << "C++ file I/O is easy!" << endl;
        outFile.close();
    } else {
        cout << "Unable to open file." << endl;
    }
    return 0;
}

출력

  • 파일 example.txt에 다음 내용이 저장됩니다:
This is a line in the file.
C++ file I/O is easy!

예제: 파일 읽기

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream inFile("example.txt");
    string line;
    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "Unable to open file." << endl;
    }
    return 0;
}

출력

This is a line in the file.
C++ file I/O is easy!

2. 서식화된 출력 (Formatted Output)

특징

  1. iomanip 헤더를 사용하여 출력 형식을 제어합니다.

  2. setprecision, setw, fixed 등을 활용합니다.

예제

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double pi = 3.14159265359;
    cout << "Default: " << pi << endl;
    cout << fixed << setprecision(2);
    cout << "Fixed and 2 decimal places: " << pi << endl;
    cout << setw(10) << "Aligned" << endl;
    return 0;
}

출력

Default: 3.14159
Fixed and 2 decimal places: 3.14
    Aligned

결론

C++에서 입출력은 사용자와의 상호작용 및 파일 처리에서 중요한 역할을 합니다. 기본 입출력부터 파일 입출력, 서식화된 출력까지 다양한 기능을 활용하여 효율적인 프로그램을 작성할 수 있습니다.

728x90