扫描有效整数
Scanning for a valid integer
好的,这里完全是新手,但我需要一点 help/insight 如何开始编写特定程序。我不是要求有人为我做这件事,我只是要求解决这个问题的方法,因为老实说我不确定如何开始。
我应该编写的程序是检测有效整数。然而,在这个程序中,一个有效的整数定义如下:
- 0 个或更多前导空格后跟...
- 可选的“+”或“-”后跟...
- 1 个或多个数字,后跟一个非字母数字,但不是“.”后跟一位或多位数字。
有效整数示例:“1234”、“1234”、“1234.”、“+1234”、“12+34”、“1234.”、“1234 x”和“-1234” “1234e5”、“e1234”、“1234.56”和“1234abc”的所有整数和 none 是。
到目前为止,我能想到的就是使用一堆 if 语句来检查有效整数,但我忍不住认为必须有一种比使用大量 if 语句来检查有效整数更好、更健壮的方法检查字符串的每个字符。除了使用 isdigit() 和 strtol() 之外,我想不出任何对我有用的函数?如有任何建议,我们将不胜感激。
您只需要检查循环中的每个字符并在进行过程中保持一个小状态机,直到您确定它无效或到达终点。
编辑:if 语句没有问题,或者您可以使用 switch 语句。
我可能会使用 sscanf
(或 fscanf 等)
虽然不支持完整的正则表达式,但scanf
格式字符串支持scan set
转换,这类似于正则表达式中的字符集(包括倒置的,例如%1[^a-zA-Z0-9]
匹配单个非字母数字字符)。
格式字符串中的单个 space 匹配输入中任意数量的白色 space。
看看strtol()
,它可以通过指针告诉你字符串的无效部分return。
并提防热情的示例代码。请参阅手册页以了解全面的错误处理。
将您的话放入代码中 - 一次一个。伪代码如下
// to detect valid integers.
success_failure detect valid integers(const char *s) {
// 0 or more leading white spaces followed by...
while (test_for_whitespace(*s)) s++;
// an optional '+' or '-' followed by...
if (test_if_sign(*s)) s++;
// 1 or more digits, ...
digit_found = false;
while (test_if_digit(*s)) { s++; digit_found = true; ]
if (!digit_found) return fail;
// followed by a non-alphanumeric, but not a '.' followed by 1 or more digits.
if (is_a_non_alphanumeric_non_dp_not_null(*s)) {
s++;
digit_found = false;
while (test_if_digit(*s)) { s++; digit_found = true; ]
if (!digit_found) return fail;
}
if (is_not_a_null_character(*s)) return fail;
return success;
}
好的,这里完全是新手,但我需要一点 help/insight 如何开始编写特定程序。我不是要求有人为我做这件事,我只是要求解决这个问题的方法,因为老实说我不确定如何开始。
我应该编写的程序是检测有效整数。然而,在这个程序中,一个有效的整数定义如下:
- 0 个或更多前导空格后跟...
- 可选的“+”或“-”后跟...
- 1 个或多个数字,后跟一个非字母数字,但不是“.”后跟一位或多位数字。
有效整数示例:“1234”、“1234”、“1234.”、“+1234”、“12+34”、“1234.”、“1234 x”和“-1234” “1234e5”、“e1234”、“1234.56”和“1234abc”的所有整数和 none 是。
到目前为止,我能想到的就是使用一堆 if 语句来检查有效整数,但我忍不住认为必须有一种比使用大量 if 语句来检查有效整数更好、更健壮的方法检查字符串的每个字符。除了使用 isdigit() 和 strtol() 之外,我想不出任何对我有用的函数?如有任何建议,我们将不胜感激。
您只需要检查循环中的每个字符并在进行过程中保持一个小状态机,直到您确定它无效或到达终点。
编辑:if 语句没有问题,或者您可以使用 switch 语句。
我可能会使用 sscanf
(或 fscanf 等)
虽然不支持完整的正则表达式,但scanf
格式字符串支持scan set
转换,这类似于正则表达式中的字符集(包括倒置的,例如%1[^a-zA-Z0-9]
匹配单个非字母数字字符)。
格式字符串中的单个 space 匹配输入中任意数量的白色 space。
看看strtol()
,它可以通过指针告诉你字符串的无效部分return。
并提防热情的示例代码。请参阅手册页以了解全面的错误处理。
将您的话放入代码中 - 一次一个。伪代码如下
// to detect valid integers.
success_failure detect valid integers(const char *s) {
// 0 or more leading white spaces followed by...
while (test_for_whitespace(*s)) s++;
// an optional '+' or '-' followed by...
if (test_if_sign(*s)) s++;
// 1 or more digits, ...
digit_found = false;
while (test_if_digit(*s)) { s++; digit_found = true; ]
if (!digit_found) return fail;
// followed by a non-alphanumeric, but not a '.' followed by 1 or more digits.
if (is_a_non_alphanumeric_non_dp_not_null(*s)) {
s++;
digit_found = false;
while (test_if_digit(*s)) { s++; digit_found = true; ]
if (!digit_found) return fail;
}
if (is_not_a_null_character(*s)) return fail;
return success;
}