본문 바로가기

MFC(Window Programming)

ifstream, ostream, stringstream, std::getline

728x90

 

 

C++에서 getline 함수 사용 예제

C++의 getline 함수는 입력 스트림에서 한 줄씩 문자열을 읽어오는 함수입니다. 이 함수는 파일 입출력, 문자열 처리, 사용자 입력 등에 사용됩니다. 아래는 ifstream, ostream, stringstream, string 클래스와 함께 getline을 사용하는 간단한 예제입니다.

예제 코드

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main() {
    // 파일에서 한 줄씩 읽기 (ifstream 사용)
    std::ifstream inputFile("example.txt");
    if (inputFile.is_open()) {
        std::string line;
        while (std::getline(inputFile, line)) {
            std::cout << "File line: " << line << std::endl;
        }
        inputFile.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    // 콘솔에 출력하기 (ostream 사용)
    std::ostream &output = std::cout;
    output << "This is an example of ostream output." << std::endl;

    // 문자열 스트림 처리 (stringstream 사용)
    std::stringstream ss;
    ss << "This is a stringstream example." << std::endl;
    std::string str;
    std::getline(ss, str);
    std::cout << "String from stringstream: " << str << std::endl;

    // 사용자 입력 받기 (getline과 string 사용)
    std::string input;
    std::cout << "Enter a line of text: ";
    std::getline(std::cin, input);
    std::cout << "You entered: " << input << std::endl;

    return 0;
}

설명

  • ifstream: 파일에서 한 줄씩 데이터를 읽습니다.
  • ostream: 콘솔에 데이터를 출력합니다.
  • stringstream: 문자열을 스트림처럼 처리할 수 있습니다.
  • getline: 사용자 입력이나 파일, 문자열에서 한 줄씩 데이터를 읽어옵니다.

이 예제는 C++에서 다양한 스트림을 활용하여 getline 함수를 사용하는 방법을 보여줍니다. 파일 입출력, 문자열 처리, 사용자 입력 등을 간편하게 처리할 수 있습니다.

728x90