- 입출력 라이브러리는 buffer를 활용해 데이터를 모아 입력 또는 출력 요청을 수행한다. 버퍼를 비우는 경우는 아래와 같다.
- buffer full
- 버퍼에 들어있는 data를 입력 또는 출력 요청받음
- 개발자가 명시한 코드
- + 를 이용한 문자열 결합(concatenate)
- 문자열 + 문자열 / 문자열 + 문자열 리터럴. 왼쪽 우선 결합성
- 연산자 오버로드: 피연산자 타입에 따라 연산자가 다른 의미로 동작한다.
- +를 숫자끼리 썼을 때와 문자열끼리 썼을 때 기능을 달리한다.
- const 상수는 선언과 동시에 초기화해야하며, 소멸할 때까지 그 값을 변경할 수 없다.
연습문제
//1-0
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::cout << "Please enter your first name: ";
std::string name;
std::cin >> name;
const std::string greeting = "Hello, " + name + "!";
const std::string spaces(greeting.size(), ' ');
const std::string second = "* " + spaces + " *";
const std::string first(second.size(), '*');
std::cout << std::endl;
std::cout << first << std::endl;
std::cout << second << std::endl;
std::cout << "* " << greeting <<" *" << std::endl;
std::cout << second << std::endl;
std::cout << first << std::endl;
return 0;
}
//1-1
#include <iostream>
#include <string>
using namespace std;
int main()
{
const std::string hello ="Hello";
const std::string message = hello + ", world" + "!";
//문자열 리터럴 끼리 +결합은 불가능 하지만 왼쪽 우선 연산이라 가능
std::cout << message << std::endl;
return 0;
}
//1-6
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::cout << "What is your name? ";
std::string name;
std::cin >> name; //first cin
// name에 첫 번째 단어 "Samuel" flush하여 buffer에는 "Beckett" 남음
std::cout << "Hello, " << name << std::endl << "And what is yours? ";
std::cin >> name; //second cin
//buffer에 이미 단어가 있으므로 새로 입력을 받지 않고 "Beckett"을 name에 flush
//buffer of name is empty now
std::cout << "Hello, " << name << "; nice to meet you too!" << std::endl;
return 0;
}
//결과
What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Beckett; nice to meet you too!
- cin 수행
- buffer가 비어 있다면 프로그램 실행을 중단하고 사용자에게 입력을 요청하여 buffer에 단어를 저장한 후, string 변수에 flush
- 해당 string 변수의 buffer에 이미 단어가 들어있다면, 프로그램을 중단하여 사용자 입력을 받을 필요없이 buffer 내용을 string 변수에 flush