이 글에서는 사용자로부터 입력받은 문자열이 정수 문자열인지, 아니면 일반 문자열인지 판별하는 방법을 살펴봅니다. 여기서 정수 문자열이란 문자열을 구성하는 모든 문자가 0~9 범위의 숫자인 경우를 의미합니다.
기본 원리
해결 방법은 매우 간단합니다. 문자열의 각 문자를 처음부터 끝까지 하나씩 순회하면서 해당 문자가 숫자인지 검사하면 됩니다. 모든 문자가 숫자라면 true를 반환하고, 중간에 숫자가 아닌 문자를 발견하면 즉시 false를 반환합니다.
C++ 구현 예제
#include <iostream>
using namespace std;
bool isNumeric(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false; // 숫자가 아닌 문자를 발견하면 false 반환
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isNumeric(str))
cout << "This is a Number" << endl;
else
cout << "This is not a number";
}실행 결과
입력이 숫자로만 이루어진 경우:
Enter a string: 5687 This is a Number
문자가 섞여 있는 경우:
Enter a string: 584asS This is not a number
참고: 더 간결한 방법 (C++11 이상)
C++11 이상을 사용한다면 std::all_of 알고리즘과 람다식을 활용해 같은 로직을 한 줄로 표현할 수 있습니다.
#include <algorithm>
#include <cctype>
bool isNumeric(const string& str) {
return !str.empty() &&
std::all_of(str.begin(), str.end(), ::isdigit);
}이 방식은 빈 문자열을 숫자로 오판하지 않도록 !str.empty() 조건을 함께 검사한다는 점도 유의하세요. 또한 isdigit 함수를 사용하려면 <cctype> 헤더를 포함해야 합니다.