首页 文章

比较C中两个while循环中两个文件的字符串

提问于
浏览
0

我正在尝试找到两个txt文件中的字符串(一个来自argv [2],一个来自stdin),但我的循环只测试第一个文件中的第一行字符串和第二个文件的其余部分 . 我似乎无法弄清楚为什么我的程序尽管有while循环但没有回到每个票证的“检查位置” .

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

#define BUFLEN (15)

int main(int argc, char *argv[]) {

char buf[15];
char buflocation[6];
char location[6];

FILE *fp = fopen(argv[2],"r");


while (fgets(buf, BUFLEN, stdin) != NULL) {
    int i;

    for (i = 0; i<4; i++){
        location[i] = buf[i];

    }

    printf("location of ticket we are testing is %s\n",location);

    while (fgets(buflocation,sizeof(buflocation),fp) != NULL){


            printf("location to check against:%s",buflocation);
                if (strncmp(location,buflocation,4) == 0){
                        printf("this ticket is valid %s\n",buf);
                    }
    }
}



fclose(fp);
return 0;

}

这是输出

location of ticket we are testing is 1111
location to check against:0101
location to check against:0027
location to check against:1009
location to check against:0077
location to check against:1111
this ticket is valid 111122222220
location of ticket we are testing is 1111
location of ticket we are testing is 9876
location of ticket we are testing is 4526
location of ticket we are testing is 7368

所以,如果我的下一张票是100967789654,那么它应该也是有效的,因为1009是一个有效的位置,但它只是没有读入第二行 . 我没有正确宣布我的时间陈述吗?

2 回答

  • 1

    内部while循环保持将文件读取到最后 . 在外循环的第二次迭代中,文件已经位于文件末尾 . 要强制重新读取,您需要将文件重新定位到开头:

    fseek(fp, 0, SEEK_SET);
    
  • 1

    填充char数组时,需要使用 '\0' 字符终止它

    例:

    #include <stdio.h>
    #include <string.h>
    
    main()
    {
       char location[10];
    
       location[0]='a';
       location[1]='b';
       location[2]='c';
       location[3]='\0'; // not adding this is undefined behavior
    
       printf("%s", location);
    }
    

相关问题