Skip to content

Instantly share code, notes, and snippets.

@jiro4989
Last active October 29, 2021 22:41
Show Gist options
  • Save jiro4989/c563061eac4799abb3ec7d63a5f5bc26 to your computer and use it in GitHub Desktop.
Save jiro4989/c563061eac4799abb3ec7d63a5f5bc26 to your computer and use it in GitHub Desktop.
C言語で文字列が自然数かどうかを判定する関数
#include <stdio.h>
const int TRUE = 1;
const int FALSE = 0;
int is_natural(char *s) {
if (s[0] == '\0' || s[0] == '0') return FALSE;
for (int pos = 0; TRUE; pos++) {
char ch = s[pos];
if ('0' <= ch && ch <= '9') continue;
if (ch == '\0') break;
return FALSE;
}
return TRUE;
}
void assert_eq(int want, int got) {
if (want == got) {
printf("PASS\n");
return;
}
printf("FAIL\n");
}
int main(void) {
assert_eq(TRUE, is_natural("1"));
assert_eq(TRUE, is_natural("9"));
assert_eq(TRUE, is_natural("10"));
assert_eq(TRUE, is_natural("19"));
assert_eq(TRUE, is_natural("99"));
assert_eq(TRUE, is_natural("65536"));
assert_eq(FALSE, is_natural("0"));
assert_eq(FALSE, is_natural("01"));
assert_eq(FALSE, is_natural("-1"));
assert_eq(FALSE, is_natural(""));
assert_eq(FALSE, is_natural("a"));
assert_eq(FALSE, is_natural("123a"));
}

動作確認

gcc is_natural.c
./a.out

実行結果

PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment