Tech Blog/C and C++
C언어 - fcmp 실습 (문자 및 숫자 비교)
EXPRESSIONS HAVE POWER
2021. 6. 14. 13:06
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define NUM 1
#define CHARCT 2
int numcmp(const char*, const char*); // 함수 numcmp 선언
void fcmp(int(**p)(const char *, const char *), char*, char*);// 함수 fcmp 선언
int main()
{
char s[80], t[80];
int (*ptr)(const char*, const char*); // 변수 ptr 선언
scanf_s("%s %s", s, t);
fcmp(&ptr, s, t); // 함수 fcmp 콜
printf("%d\n", ptr(s, t));
return 0;
}
//--------------- 함수 numcmp 정의 ---------------------
int numcmp(const char* ps, const char* pt)
{
float a, b;
a = atof(ps);
b = atof(pt);
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
// --------------- 함수 fcmp 정의 ---------------------
void fcmp(int(**p)(const char*, const char*), char* ps, char* pt)
{
int cond;
cond = NUM;
if (*ps == '-')
ps++;
while (cond == NUM && *ps != NULL)
if (isdigit(*ps) || *ps == '.')
ps++;
else
cond = CHARCT;
if (*pt == '-')
pt++;
while (cond == NUM && *pt != NULL)
if (isdigit(*pt) || *pt == '.')
pt++;
else
cond = CHARCT;
if (cond == NUM)
*p = numcmp;
else
*p = strcmp;
}
유의사항
1 . scanf_s 는 visual studio 전용 코드이므로 웬만하면 scanf를 사용할 것.
2. scanf를 사용할 때는 #include 보다 위에 #define _CRT_SECURE_NO_WARNINGS 넣어서 사용할 것.
3. 이번 코드에는 중괄호 {}가 생략 되었는데, 아주 끔찍한 코드라고함...(개발자커뮤니티에서)
앞으로는 { } 꼬박꼬박 넣으며 작성할 것.