如何使if语句打印需要结果?

时间:2020-08-28 14:52:01

标签: c if-statement

此代码有一个问题。问题出在

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;
}

1 个答案:

答案 0 :(得分: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);