이 포스팅은 Object Oriented Programming 시리즈 23 편 중 9 번째 글 입니다.

  • Part 1 - 01: Introduction
  • Part 2 - 02: Identifier, Variable, constant, Std IO, Operator
  • Part 3 - 03: Functions #1 - Calling (호출)
  • Part 4 - 04: Functions #2 - Local, Global Variable
  • Part 5 - 05: Functions #3 - Recursion Function, Reference Variable (재귀함수)
  • Part 6 - 06: Functions #4 - Reference Variable vs. Pointer
  • Part 7 - 07: Functions #5 - CallbyValue, CallbyReference
  • Part 8 - 08: Selection and Repetition
  • Part 9 - This Post
  • Part 10 - 10: String library, rand(), srand()
  • Part 11 - 11: Pointer, Function Pointer
  • Part 12 - 12: Array, Vector (정적배열, 동적배열)
  • Part 13 - 13: class, object
  • Part 14 - 14: this, operator overloading
  • Part 15 - 15: friend, static, destructor
  • Part 16 - 16: Inherence (상속)
  • Part 17 - 17: Static Binding, Dynamic Binding, Header File
  • Part 18 - 18: Generic Programming, Template
  • Part 19 - 19: List Container
  • Part 20 - 20: Iterator (반복자)
  • Part 21 - 21: algorithm Library
  • Part 22 - 21: functional, lambda function
  • Part 23 - 22: Exception handling
▼ 목록 보기

fstream

Reading from file

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

int main(){
    string line;
    ifstream myfile("input.txt");

    if (myfile.is_open()){
        while(getline (myfile, line)){	// string의 함수 getline
   										// myfile 에서 1줄씩 읽어들여 line 스트링 변수에넣는다.
            							// 없으면 0을 반환한다.
            							// 있으면 1을 반환한다.
            cout << line << endl;
        }
        myfile.close();
    }
    else {
        cout << "unable to open file";
    }

    return 0;
}

Writing to file

#include <iostream>
#include <fstream>

int main(){
    ofstream myfile("output.txt");
    myfile << "writing this to a file.\n";
    myfile.close();

    return 0;
}

Formatting Data

#include <fstream>
#include <iostream>

using namespace std;

int main(){
    ofstream fout("output.txt");
    int a = 123;
    double b = 12.12345678;

    fout.width(15);	// 값을 출력하는데 있어 기본 칸 크기
    fout << a << endl;
    fout.width(15);
    fout.precision(10);
    fout << b << endl;

    fout.close();
    return 0;
}
            123
12.12345678

cin.unsetf()

cin.unsetf(ios::skipws);	// 파일을 읽을 때 공백 문자가 나오면 버린다.