【发布时间】:2020-05-01 03:24:41
【问题描述】:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
_Bool check_domain(char *domain) {
int str_count = 0, x = strlen(domain), y = 0;
if (domain[x-1] == '.' || domain[0] == '.'){
return false; //if there is a period at start or end
}
else{
while (domain[y]){
if (str_count==2){
return false; //if 2 consecutive periods
}
if (domain[y] == 46 || 65<=domain[y]<=90 || 97<=domain[y]<=122){ //if character is period or alphanumeric
if (domain[y] == '.'){
str_count += 1;
}
else{
str_count = 0;
}
}
else{ // if character is non period non alphanumeric
return false;
}
y += 1;
}
}
return true;
}
int main(void){
char domain[] = "nus@edu.sg";
printf("%d",check_domain(domain));
}
编辑: 感谢您的回复,现在对这个主题有更多的了解。 除了在结尾或开头没有句点,也没有两个连续的句点之外,字符串内不应有非句点、非字母数字字符。 由于我无法弄清楚的原因,对于字符串中存在非句点、非字母数字字符的情况,此代码无法返回 false。
【问题讨论】:
-
你遇到了什么错误?
-
您至少缺少 3 个必需的
#include指令:<stdio.h>(对于printf)、<string.h>(对于strlen)和<stdbool.h>(对于false和true)。void main()应该是int main(void)。这些不是唯一的错误。始终包含您的整个程序(请参阅minimal reproducible example)以及您在编译时遇到的实际复制粘贴错误。 -
你有
while (domain[x]) {},其中x是domain的字符串长度。这意味着domain[x]将始终是字符串末尾的空终止符,因此while 循环将永远不会运行。看起来您应该使用for (x = 0; domain[x]; x++) {}而不是while循环 -
不要为变量使用无意义的名称。
i传统上用作索引,而在这里您使用它来保存您找到的周期数。如果您使用更好的名称,例如periods_found,那么代码会更清晰。同样,可能在您使用x的地方使用i。 -
大家好,感谢您的帮助。我已经实施了您的建议,但仍然存在问题。你能告诉我哪里出错了吗?