如何解决如何使if语句打印需要结果?
if语句中的问题
event.inputTranscript
每当我输入13个字符但不是从文件中输入时,它就会给我一条else语句的消息,但也会打印if(all_digits(to_find) && strlen(to_find) == 13)
。尽管Found. Hello World!
处于if语句中。不应打印。如何使if语句正常工作?
Found. Hello World!
另一部分代码
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int all_digits(char *s){
for (; *s!=0; s++){
if (!isdigit(*s)){
return 0;
}
}
return 1;
}
解决方法
要运行多个测试而无需级联if-thens,可以将错误标志与一次性循环一起使用,如下所示:
int err = 0; /* Be optimistic! (0 indicates success) */
do {
if (!test1-passed) {
err = 1;
break;
}
if (!test2-passed) {
err = 2;
break;
}
...
if (!testN-passed) {
err = N;
break;
}
printf("Success! All tests passed");
} while (0);
if (err) {
printf("Test %d failed",err);
}
针对您的特定问题,代码可能看起来像这样
... /* definitions here */
int err = 0; /* Be optimistic! (0 indicates success) */
do {
... /* input here */
do {
if (!all_digits(to_find)) {
err = 1;
break;
}
if (strlen(to_find) != 13) {
err = 2;
break;
}
{
err = 3 /* be pessimistic! */
while(fgets(line,200,fr)){
/* word = strtok(line,"\n"); */ /* word is not needed. */
strcpy(save,line); /* Introducing save here is not necessary,all following operation can be applied to line. */
if (strstr(save,to_find)){
char *wordone = strtok(save,",");
while (wordone != NULL){
printf("Here are your details: %s\n",wordone);
wordone = strtok(NULL,");
err = 0; /* Phew,we are lucky! */
}
}
}
if (err) {
break;
}
}
printf("Success! All tests passed");
} while (0);
if (err) {
printf("Test %d failed",err);
}
} while (err);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。