Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C/C++를 사용하여 입력이 정수인지 확인하는 방법은 무엇입니까?

<시간/>

여기에서 주어진 입력이 정수 문자열인지 일반 문자열인지 확인하는 방법을 볼 것입니다. 정수 문자열은 0 – 9 범위에 있는 모든 문자를 포함합니다. 솔루션은 매우 간단합니다. 각 문자를 하나씩 살펴보고 숫자인지 여부를 확인하면 됩니다. 숫자이면 다음을 가리키고 그렇지 않으면 false 값을 반환합니다.

예시

#include <iostream>
using namespace std;
bool isNumeric(string str) {
   for (int i = 0; i < str.length(); i++)
      if (isdigit(str[i]) == false)
      return false; //when one non numeric value is found, return 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