Menu
CoddyTech

불리언과 조건문

Coddy의 C 개발자를 위한 C++ 코스 레슨. 48개 중 5번째.

C에서는 C17의 stdbool.h를 통해 bool을 사용할 수 있고, C++에는 기본 제공 bool 유형이 있습니다. 두 언어 모두 스칼라 조건을 허용하지만, 명시적인 술어를 사용하면 의도가 더 명확해집니다. 스트림에서 boolalpha를 사용하면 숫자 플래그 대신 true 또는 false를 출력합니다.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(void){
bool ready=5!=0 && 2<4;puts(ready?"true":"false");
return 0;
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
std::cout<<std::boolalpha<<(5!=0 && 2<4)<<"\n";
}

각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.

challenge icon

챌린지

쉬움

입력: 정수 나이와 회원 여부 플래그(0 또는 1). 16세 이상인 회원을 입장시키고 Boolean 값을 반환합니다.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있습니다. 공개 시그니처는 유지하세요. 잠금된 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작을 별도로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 signed int 범위에 들어갑니다. 별도 언급이 없으면 텍스트는 ASCII입니다.

직접 해보기

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,m;in>>a>>m;std::cout<<std::boolalpha<<admitted(a,m!=0)<<"\n";
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 C++의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러