如何停止一次又一次地重复相同的数据?

How to stop repeating the same data again and again?

在这段代码中,我试图打印文件中除了我用身份证号码选择的行之外的剩余行。但是数据向我展示了结果 like

输出

data1....
Above are the remaining lines
data2....
Above are the remaining lines
data3....
Above are the remaining lines

我希望在打印完所有数据后在最后重复 Above are the remaining lines

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  FILE * fp1 = fopen("file.csv", "r");
  char string[200], toFind[200];
  char* lines = NULL;
  char* result = NULL; 

  printf("Enter your ID Card number: ");
  scanf("%s", toFind);

  while(fgets(string, 200, fp1)){
      lines = strtok(string, "\n");
      result = strstr(lines, toFind);

      if(!result){
         printf("%s\n", lines);
         printf("Above are the remaining lines\n");      
      }
  }    
   fclose(fp1);
 return 0; 
}

解决方法是将要打印的字符串放在while.

之外

为了完成,您可以使用 flag 仅打印 "Above are the remaining lines" 如果实际上还有剩余行:

Live demo

int flag = 0; //flag declaration

while (fgets(string, sizeof string, fp1)) { 
    //lines = strtok(string, "\n"); //this is doing nothing meaningful
    result = strstr(string, toFind); //use string instead
    if (!result)
    {
        printf("%s\n", string);
        if (!flag)
            flag = 1;
    }
}
if (flag)
    printf("Above are the remaining lines\n");

示例:

文件内容:

1234....
4567....
8910....

输入:

4567

输出:

1234....
8910....
Above are the remaining lines