fstream

Reading from file

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
int main(){
    string line1;
    string line2
    ifstream myfile("input.txt");
    
    if (myfile.is_open()){
    	if(!myfile.eof()){
        // end of file ์ด ์•„๋‹ˆ๋ฉด ๊ณ„์† ์ง„ํ–‰. end of file ์ด๋ฉด 1์„ ๋ฐ˜ํ™˜
        fin >> line1;	// ์ด๋ ‡๊ฒŒ ์“ฐ๋ฉด ๊ณต๋ฐฑ, ์ŠคํŽ˜์ด์Šค ๊ธฐ์ค€์œผ๋กœ ํ•˜๋‚˜์”ฉ ๋“ค์–ด๊ฐ„๋‹ค!
        cout << line1 << endl;
          while(getline (myfile, line)){	// string์˜ ํ•จ์ˆ˜ getline
                // myfile ์—์„œ 1์ค„์”ฉ ์ฝ์–ด๋“ค์—ฌ line ์ŠคํŠธ๋ง ๋ณ€์ˆ˜์—๋„ฃ๋Š”๋‹ค.
                // ์—†์œผ๋ฉด 0์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
                // ์žˆ์œผ๋ฉด 1์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
              cout << line2 << 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);	// ํŒŒ์ผ์„ ์ฝ์„ ๋•Œ ๊ณต๋ฐฑ ๋ฌธ์ž๊ฐ€ ๋‚˜์˜ค๋ฉด ๋ฒ„๋ฆฐ๋‹ค.