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;
}
#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); // ํ์ผ์ ์ฝ์ ๋ ๊ณต๋ฐฑ ๋ฌธ์๊ฐ ๋์ค๋ฉด ๋ฒ๋ฆฐ๋ค.