STUDY BLOG
명품 C++ programming Chapter 02 예제 본문
명품 C++ programming Chapter 02 예제 연습
예제 2-1 기본적인 C++ 프로그램
// cout과 << 연산자를 이용하여 화면에 출력
#include <iostream>
int main() {
std::cout << "Hello\n";
std::cout << "첫 번째 맛보기 입니다.";
return 0;
}
예제 2-2 cout과 <<를 이용한 화면 출력
#include <iostream>
double area(int r);
double area(int r){
return 3.14*r*r;
}
int main(){
int n=3;
char c='#';
std::cout << c << 5.5 << '-' << n << "hello" << true << std::endl;
std::cout << "n+5 = " << n+5 << '\n';
std::cout << "면적은 " << area(n);
}
예제 2-3 cin과 >>로 키 입력 받기
#include <iostream>
using namespace std;
int main(){
cout<< "너비를 입력하세요 >>";
int width;
cin >> width;
cout<< "높이를 입력하세요 >>";
int height;
cin >> height;
int area = width*height;
cout<< "면적은 " << area << "\n";
}
예제 2-4 키보드에서 문자열 입력받고 출력
#include <iostream>
using namespace std;
int main(){
cout << "이름을 입력하세요 >>";
char name[11];
cin >> name;
cout << "이름은 " << name << "입니다\n";
}
예제 2-5 C-스트링을 이용하여 암호가 입력되면 프로그램을 종료하는 예
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char password[11];
cout << "if you want to end this program, enter password" << endl;
while(true){
cout<< "enter password >>";
cin >> password;
if(strcmp(password,"C++")==0){
cout<< "program end" << endl;
break;
}
else
cout<< "password error" <<endl;
}
}
예제 2-6 cin.getline()을 이용한 문자열 입력
#include<iostream>
using namespace std;
int main(){
cout<< "enter address >>";
char address[100];
cin.getline(address, 100, '\n');
cout << "address is " << address << "\n|;
}
예제 2-7 string 클래스를 이용한 문자열 입력 및 다루기
#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<< "(힌트 : 첫 글자는 " << elvis[0] << ")?";
getline(cin, singer);
if(singer == elvis)
cout << "정답";
else
cout << "오답. " << elvis << "입니다." << endl;
}
오타 지적 및 조언은 언제나 환영합니다.
'Software > C++' 카테고리의 다른 글
명품 C++ programming Chapter 07 예제 (0) | 2020.11.25 |
---|---|
명품 C++ programming Chapter 06 예제 (0) | 2020.11.22 |
명품 C++ programming Chapter 05 예제 (0) | 2020.11.20 |
명품 C++ programming Chapter 04 예제 (1) | 2020.11.02 |
명품 C++ programming Chapter 03 예제 (1) | 2020.10.29 |