【发布时间】:2011-07-11 03:05:36
【问题描述】:
我有一个函数应该传递一个带有两个数字的字符串(作为正则表达式:/-?[0-9]+ -?[0-9]+/)并返回第二个。
我决定程序应该进行错误检查。首先,它应该测试字符串是否实际上是所需的形式;其次,它应该确保第一个数字(不返回的)是连续的。
现在我已经编程了很长时间,这不是一项艰巨的任务。 (由于数字不需要适合机器词,这使得它稍微困难一些。)但我的问题是我应该如何 这样做,而不是我如何可以 .我提出的所有解决方案都有些难看。
- 我可以使用一个全局变量来保存这些值并比较它们(或者如果它是
NULL,则将值保留在那里);这似乎是错误的事情。 - 我可以通过引用传递一个或两个返回值和最后/当前行的第一个数字并修改它们
- 我可以使用返回值来给出一个布尔值,因为有/没有错误
- 等
因此,任何与在 C 中处理此类错误检查的正确方法有关的任何想法都将受到欢迎。
这与更理论化的question I asked on cstheory 有关。供参考,这里是函数:
char*
scanInput(char* line)
{
int start = 0;
while (line[start] == ' ' || line[start] == '\t')
start++;
if (line[start] == '#')
return NULL; // Comment
if (line[start] == '-')
start++;
while (line[start] >= '0' && line[start] <= '9')
start++;
while (line[start] == ' ' || line[start] == '\t')
start++;
int end = start;
if (line[end] == '-')
end++;
while (line[end] >= '0' && line[end] <= '9')
end++;
if (start == end)
return NULL; // Blank line, or no numbers found
line[end] = '\0';
return line + start;
}
它是这样调用的:
while(fgets(line, MAX_LINELEN, f) != NULL) {
if (strlen(line) > MAX_LINELEN - 5)
throw_error(talker, "Maximum line length exceeded; file probably not valid");
char* kept = scanInput(line);
if (kept == NULL)
continue;
BIGNUM value = strtobignum(kept);
if (++i > MAX_VECLEN) {
warning("only %d terms used; file has unread terms", MAX_VECLEN);
break;
}
// values are used here
}
【问题讨论】:
标签: c error-handling validation