#include <iostream>
#include <string>
using namespace std;
int main () {
// string을 선언하고 초기화
string word = "fred";
cout << word.length << '\n'; // 4개의 character로 구성되어 있으므로 4가 출력됨
if (word.empty())
cout << "empty\n";
else
cout << "not empty\n" // not empty가 출력될 것
word.clear(); // 빈 string으로 만듦
if (word.empty())
cout << "empty\n";
else
cout << "not empty\n" // empty가 출력될 것
word = "good";
cout << word << '\n';
word += "-bye";
cout << word << '\n'; //good-bye 출력될 것
cout << word[0] << '\n'; // g 출력
cout << word[word.length()-1] << '\n';
cout << word.substr(2,5); // index가 2인거 부터 5글자
cout << word.substr(2); // index가 2인거 부터 끝까지
string first = "ABC", last = "XYZ";
cout << first + last << '\n'; // ABCXYZ 출력
}
File Input & Output
file의 input & output의 흐름도
[C++에서의 file stream]
- ifstream : 파일로 부터 읽어 올거야! - ofstream : 파일에 쓸거야! - fstream : 파일에 읽고 쓸거야! (단, 읽기를 위한 것인지 쓰기를 위한것인지 혼돈이 생길 수 있어 잘 쓰지는 않음)
[File stream을 생성 또는 연결을 끊기]
- file stream 생성 : ifstream[] / ofstream[] / fstream[] - file stream 연결 : open() - file stream 연결 해제 : close()
[File 읽기 및 쓰기]
// Reading from file
int main() {
ifstream fsTemp;
int a;
fsTemp.open (“temp.txt");
fsTemp >> a;
cout << a;
fsTemp.get(a); /*6번 줄과 동일한 의미*/
cout << a;
}
// Writing to file
int main() {
ofstream fsTemp;
int a;
fsTemp.open (“temp.txt”);
cin >> a;
fsTemp << a;
fsTemp.put(a); //17번 줄과 동일한 의미
}
[Formatting Data Using control variables]
- .width() : 출력할 길이를 설정 - .fill() : 데이터의 길이보다 출력하고 싶은 길이가 더 길때, 비어있는 공간을 뭐로 채울지 설정해줌 - .precision() : 소숫점 아래 어디까지 쓸건지 설정해줌