< 2.1 C++ 프로그램의 기본 요소와 화면 출력 >
1. main() 함수
- C++ 프로그램의 실행 시작점
- 리턴 타입은 int
- main() 함수에는 return 0; 을 생략 가능하다
2. #include <iostream>
- include < 전처리기
컴파일 하기 전에 <iostream> 헤더 파일을 읽어 C++ 소스 파일 안에 삽입하라는 뜻
- 헤더 파일에는 C++ 표준 입출력을 위한 클래스와 객체가 선언되어 있음
3. 출력
형식 : std::cout <<
cout : 표준 출력 스트림 객체
std : 이름 공간
<< : 스트림 삽입 연산자, 한 줄에 여러개의 << 연산자를 사용하여 여러개의 데이터 출력 가능
ex)
std::cout << "hello\n" << "첫 번째 맛보기입니다.";
또한 기본 타입 데이터도 출력이 가능 (bool, char, short, int, float, double)
+) std::end1 : end1은 조작자라고 불리는 함수, 줄 띄워서 출력할 때 사용
2.2 namespace와 std::
namespace : 이름 충돌을 방지하기 위해 namespace 키워드를 도입
- 서로 다른 이름 공간 안에 선언된 이름들은 별개의 이름으로 취급
- 선언 방법 : namespace 공간 이름 {}
- 사용 방법 : 이름공간::이름
+) :: 란? 범위 지정 연산자로서 C++ 표준 연산자
std:: : 표준 이름 공간, 모든 C++ 표준 라이브러리는 std 이름 공간에 만들어져 있음
using 지시어를 사용하면 std:: 를 생략하도록 할 수 있음
using std::cout //cout; 에 대해서만 std:: 생략
using namespace //std; 이름 공간에 선언된 모든 이름에 std:: 생략
2.3 키 입력 받기
cin 과 >> 연산자를 이용한 키 입력
- 둘 다 <iostream> 헤더 파일에 선언되어 있다
- bool, char, short, int, float, double 에 대해 입력 가능
int width;
cin >> width; //width에 값 입력
char c;
cin >> c //c에 값 입력
- 여러 값을 입력 받을 수도 있다. 한 문장에 여러 값을 띄어쓰기 하여 입력받을 수 있다.
#include <iostream>
using namespace std;
int main() {
int width, height;
cout << "너비 높이";
cin >> width >> height; // 23 36 입력하면
cout << width << "\n" << height << "\n"; // width 값인 23, height 값인 36 출력
}
cin 객체
- 표준 입력 스트림 객체
>> 연산자
- 스트림 추출 연산자
- enter 키를 칠 때 >> 연산자가 cin의 입력 버퍼에서 키 값을 끌어내어 변수에 저장한다
2.4 키보드로 문자열 입력
C++ 문자열 입력 방식은 두 가지
1. C-스트링
char 배열을 뜻함, C언어와의 호환성
char name1[6] = {'G', 'r', 'a', 'c', 'e', '\0'}; //name1은 문자열 'Grace'
char name2[5] = {'G', 'r', 'a', 'c', 'e'}; //name2은 문자열 아님. 단순 문자 배열
char name3[10] = {'G', 'r', 'a', 'c', 'e'}; //문자열 뒤에 남은 4개의 원소들은 모두 '\0'으로 초기화
C 프로그래밍에서 사용해왔던 strcpy(), strcmp(), strlen() 등 C 라이브러리 함수들을 그대로 사용 가능 (#include <cstring> 로 cstring 헤더 파일을 include 해야 사용 가능)
- cin 을 이용한 문자열 입력
#include <iostream>
using namespace std;
int main() {
cout << "이름을 입력하세요\n";
char name[11]; //한글은 5글자(한 문자가 2 byte), 영어는 10글자 저장 가능
cin >> name; //빈칸 없이 키 입력 (공백 문자 만나면 그 전까지 입력된 문자들을 하나의 문자열로 인식)
cout << "이름은 " << name << "입니다\n";
}
- cin.getline() 을 이용한 공백이 포함된 문자열 입력
cin.getline(char buf[], int size, char delimitChar) // 원형
char address[100];
cin.getline(address, 100, '\n'); // enter 키를 구분 문자로 지정하여 문자열 입력받는 예시
2. String 클래스
- 문자열의 크기에 제역이 없고, 문자열을 다루기 쉽다
- #include <string> 헤더 파일 include 필요
#include <iostream>
#include <string>
using namespace std;
int main() {
string song("Falling in love with you");
string elvis("Elvis Presley");
string singer;
cout << song + " 를 부른 가수는";
cout << "(힌트 : 첫글자는 " << elivs[0] << ")?"; //elvis string 의 첫 글자
getline(cin, singer); // '\n' 생략
if (singer == elvis)
cout << "맞았습니다.";
else
cout << "틀렸습니다." + elvis + "입니다" << end1;
}
2.5 #include <iostream>
- #include 문에 지정된 <헤더 파일>의 텍스트를 #include 문이 있던 그 자리에 삽입하여 헤더 파일을 확장한다
- 2003년 C++ 표준부터 헤더 파일에 확장자를 붙이지 않는다
<헤더파일>과 "헤더파일"의 차이 : <헤더파일>은 컴파일러가 설치된 폴더에 있고, "헤더파일" 은 개발자 자신이 만든 헤더파일을 사용하는 경우에 이 방법을 사용한다
- 헤더 파일에는 무엇이 들어있는가? 선언만(원형) 들어있고, 컴파일 할 때 호풀이 정확한지 판단하는 데 사용된다.
실습문제
1
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 100){
for (int j=0;j<10;j++){
cout << i << "\t";
i++;
}
cout << "\n";
}
}
2
#include <iostream>
using namespace std;
int main() {
for (int i=1; i<10; i++){
for (int j=1; j<10; j++){
cout << j << "x" << i <<"="<<i*j<<'\t';
}
cout << "\n";
}
}
3
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "두 수를 입력하라>>";
cin >> a >> b;
if (a>b)
cout << "큰 수 = " << a;
else
cout << "큰 수 = " << b;
}
4
#include <iostream>
using namespace std;
int main() {
float a,b,c,d,e;
cout << "5개의 실수를 입력하라>>";
cin >> a >> b >> c >> d >> e;
float max = a;
if (max < b)
{
max = b;
}
if (max < c)
{
max = c;
}
if (max < d)
{
max = d;
}
if (max < e)
{
max = e;
}
cout << "제일 큰 수 = " << max;
}
5.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[100];
int count = 0;
cout << "문자들을 입력하라(100개 미만)";
cin.getline(a,100);
for (int i=0; i<100; i++){
if (a[i] == 'x'){
count ++;
}
}
cout << "x의 개수는 " << count;
}
6.
#include <iostream>
#include <string>
using namespace std;
int main() {
string a,b;
cout << "새 암호를 입력하세요>>";
getline(cin,a);
cout << "새 암호를 다시 한 번 입력하세요>>";
getline(cin,b);
if (a==b){
cout << "같습니다";
} else {
cout << "다릅니다.";
}
}
7
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[100];
while (1)
{ cout << "종료하고싶으면 yes를 입력하세요>>";
cin.getline(a,100);
if (strcmp(a, "yes") == 0)
break;
}
cout << "종료합니다...";
}
8
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char name[100];
string top;
int max = 0;
cout << "5명의 이름을 ';'로 구분하여 입력하세요>>";
for (int i=0; i<5; i++){
cin.getline(name, 100, ';');
cout << (i+1) << " : " << name << "\n";
if (max < strlen(name))
{
max = strlen(name);
top = name;
}
}
cout << "가장 긴 이름은 " << top;
}
9
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char name[20];
char address[100];
char age[4];
cout << "이름은?";
cin.getline(name,20);
cout << "주소는?";
cin.getline(address, 100);
cout << "나이는?";
cin.getline(age, 4);
cout << name << ", " << address << ", " << age << "세";
}
10
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[100];
int i =0;
cout << "문자열 입력>>";
cin >> a;
for (int i=0;i<strlen(a);i++){
for (int j =0; j<=i;j++){
cout << a[j];
}
cout << "\n";
}
}
11
#include <iostream>
using namespace std;
int main() {
int n=0;
int sum = 0;
cout << "끝 수를 입력하세요>>";
cin >> n;
for (int k=0;k<=n;k++){
sum += k;
}
cout << "1에서 " << n << "까지의 합은 " << sum << "입니다.\n";
}
12
#include <iostream>
using namespace std;
int sum(int a, int b);
int main() {
int n=0;
cout << "끝 수를 입력하세요>>";
cin >> n;
cout << "1에서 " << n << "까지의 합은 " << sum(1, n) << " 입니다.\n";
}
int sum(int a, int b){
int result = 0;
for (int k=a; k<=b; k++){
result += k;
}
return result;
}
13
#include <iostream>
using namespace std;
int main() {
int order;
int num;
cout << "***** 승리장에 오신 것을 환영합니다. *****\n";
while (1){
cout << "짬뽕:1, 짜장:2, 군만두:3, 종료:4>>\t";
cin >> order;
if (order == 1){
cout << "몇인분?";
cin >> num;
cout << "짬뽕 "<<num<<"인분 나왔습니다\n";
}
else if (order == 2){
cout << "몇인분?";
cin >> num;
cout << "짜장 "<<num<<"인분 나왔습니다\n";
}
else if (order == 3){
cout << "몇인분?";
cin >> num;
cout << "군만두 "<<num<<"인분 나왔습니다\n";
}
else if (order == 4){
cout << "오늘 영업은 끝났습니다.";
break;
}
else {
cout << "다시 주문하세요!!\n";
}
}
}
14
#include <iostream>
#include <cstring>
using namespace std;
int main() {
cout << "에스프레소 2000원, 아메리카노 2300원, 카푸치노 2500원입니다.\n";
int sum, num, result = 0;
char coffee[100];
while (sum<20000){
cout << "주문>> ";
cin >> coffee >> num;
if (strcmp(coffee, "에스프레소")==0){
result = 2000*num;
sum += result;
cout << result<<"원입니다. 맛있게 드세요\n";
}
else if (strcmp(coffee, "아메리카노")==0){
result = 2300*num;
sum += result;
cout << result<<"원입니다. 맛있게 드세요\n";
}
else if (strcmp(coffee, "카푸치노")==0){
result = 2500*num;
sum += result;
cout << result<<"원입니다. 맛있게 드세요\n";
}
else {
cout << "잘 못 입력하셨어요\n";
}
}
cout << "오늘 " << sum << "를 판매하여 카페를 닫습니다. 내일 봐요~~~";
}
15
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n1, n2;
char s;
while (true){
cout << "? ";
cin >> n1 >> s >> n2;
switch (s){
case '+': cout << n1<<" + "<<n2<<" = "<<n1+n2<<"\n"; break;
case '-': cout << n1<<" - "<<n2<<" = "<<n1-n2<<"\n"; break;
case '*': cout << n1<<" * "<<n2<<" = "<<n1*n2<<"\n"; break;
case '/': cout << n1<<" / "<<n2<<" = "<<n1/n2<<"\n"; break;
case '%': cout << n1<<" % "<<n2<<" = "<<n1%n2<<"\n"; break;
default: cout << "잘 못 입력하셨습니다.\n"; break;
}
}
}
16
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char a[10000];
int count, star=0;
cout << "영문 텍스트를 입력하세요. 히스토그램을 그립니다. \n";
cout << "텍스트의 끝은 ; 입니다. 10000개까지 가능합니다.\n";
cin.getline(a, 10000, ';');
for (int i=0; i <= strlen(a); i++)
{
if (isalpha(a[i]) != 0)
{
a[i] = tolower(a[i]);
count++;
}
}
cout << "총 알파벳 수 "<<count << "\n";
for (char i = 'a';i<='z';i++){
for (int j = 0; j <= strlen(a); j++)
if (a[j] == i)
star++;
cout << i << "(" << star << ")" << " : ";
for (int k = 0; k < star; k++)
cout << "*";
cout << "\n";
star = 0;
}
}
'명품 C++' 카테고리의 다른 글
[명품 C++] 7. 프렌드와 연산자 중복 (0) | 2023.01.06 |
---|---|
[명품 C++] 6. 함수 중복과 static 멤버 (0) | 2023.01.04 |
[명품 C++] 5. 함수와 참조, 복사 생성자 (0) | 2023.01.02 |
[명품 C++] 4. 객체 포인터와 객체 배열, 객체의 동적 생성 (0) | 2022.12.30 |
[명품 C++] 3. 클래스와 객체 (0) | 2022.12.27 |