Check a Palindrome
이 초보자 연습은 Check a Palindrome을 통해 핵심 문법과 문제 해결을 훈련합니다.
Check a Palindrome이란?
이 초보자 연습은 Check a Palindrome을 통해 핵심 문법과 문제 해결을 훈련합니다.
Check a Palindrome 문제를 C와 C++의 실행 가능한 코드로 해결합니다.
중요한 점
- Compiler warning을 켜고 모두 해결하세요.
- 각 값의 type과 lifetime을 파악하세요.
- 입력과 배열 경계를 검증하세요.
C와 C++ 코드 예제
C
main.c
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "level"; size_t length = strlen(text); int palindrome = 1;
// Compare characters mirrored around the center.
for (size_t i = 0; i < length / 2; ++i)
if (text[i] != text[length - 1 - i]) { palindrome = 0; break; }
printf("%s is %sa palindrome\n", text, palindrome ? "" : "not ");
}
level is a palindrome
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string text = "level";
// equal compares the first half with a reversed view.
bool palindrome = std::equal(text.begin(), text.begin() + text.size() / 2, text.rbegin());
std::cout << text << " is " << (palindrome ? "" : "not ") << "a palindrome\n";
}
level is a palindrome
C와 C++ 비교
C와 C++ 구현을 비교하고 입력을 바꾼 뒤 추가 경계 사례를 테스트하세요.
C
C는 작은 절차형 API와 표현 세부 사항을 드러냅니다.
C++
C++는 저수준 모델을 유지하며 더 안전한 타입을 추가합니다.
연습 문제
두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.
- 잘못된 입력과 경계값을 추가하세요.
- -Wall -Wextra -Wpedantic으로 컴파일하세요.
- 선언과 구현을 분리하세요.