首页 > 解决方案 > 如何使 if 语句打印需要结果?

问题描述

这段代码有一个问题。问题出在

if语句中的问题

if(all_digits(to_find) && strlen(to_find) ==  13)

每当我输入 13 个字符但不是从文件中输入时,它就会给我一条 else 语句的消息,但Found. Hello World!也会打印。虽然Found. Hello World!在 if 语句中。它不应该被打印。如何使 if 语句正常工作?

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

另一部分代码

int main(){
  FILE * fr = fopen("file.csv", "r");

  char save[500], line[200],  to_find[50];
  int oneByOne = 0, numberOfFields=8;
  char *word = NULL;
  printf("Enter the ID card number: ");
  scanf("%s", to_find);

  if(all_digits(to_find) && strlen(to_find) ==  13){
    while(fgets(line, 200, fr)){
      word = strtok(line, "\n");
      strcpy(save, line);

      if (strstr(save, to_find)){
        char *wordone = strtok(save, ",");
        while (wordone != NULL){
          printf("Here are your details: %s\n", wordone);
          wordone = strtok(NULL, ",");
        }
      }
    }
    fclose(fr);

    printf("Found. Hello World!\n");
  }  
  else {
    printf("enter correclty\n");
  }
return 0;
}

标签: cif-statement

解决方案


要在没有级联 if-then 的情况下运行多个测试,您可以使用错误标志和一次性循环,如下所示:

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

推荐阅读