C中的strstr使用多维数组

时间:2016-03-16 21:33:58

标签: c arrays multidimensional-array strstr

对于背景,我目前正在进行一项任务,以扫描悲惨世界(在.txt文件中给我)中的角色名称(其中的一个列表是在一个单独的{{{ 1}}文件)。提到一个字符时,将哪个字符和哪一行写入.txt文件。我的代码目前将角色名称记录到.txt中,并将来自悲惨世界(不同文件,然后是整本小说)的4行摘录记录到namesArr[66][20]中。

现在到了实际问题。在尝试检查某fourlinesArr[4][100]行是否在namesArr中时,fourlinesArr将始终返回false。如果我用单个字符数组替换strstr,那么它的工作正常。有没有办法让namesArr与多维数组一起正常工作,还是应该完全使用不同的函数?

以下全部代码:

strstr

返回:

//import statements
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

//Read for Les-Mis-Names.txt
//copy and pasted fileIO.c, editing where required
const char *NAMES_FILE_PATH = "./Moodle Documents/Les-Mis-Names.txt"; // location of names file
int nameslineNum = 0;
char namesArr[66][20];

FILE *names = fopen(NAMES_FILE_PATH,  "r+" );       /* open for reading */
// This will take each row in the file and store it in namesArr.
if (names == NULL ){      /* check does names file exist etc */
    perror ("Error opening names file");
    nameslineNum = -1; /* use this as a file not found code */
} else {
    // fgets returns NULL when it gets to the end of the file
    while ( fgets(namesArr[nameslineNum], sizeof(namesArr[nameslineNum]), names ) != NULL ) {
        nameslineNum++;
    }
    fclose (names);
}
//end of fileIO.c code 

//Read for Les-Mis-4-lines
//copy and pasted fileIO.c, editing where required
const char *LES_MIS_4_LINES_FILE_PATH = "./Moodle Documents/Les-Mis-4-lines"; // location of Les-Mis-4-lines file
int fourlineslineNum = 0;
char fourlinesArr[4][100];

FILE *fourlines = fopen(LES_MIS_4_LINES_FILE_PATH,  "r+" );       /* open for reading */
// This will take each row in the file and store it in fourlinesArr.
if (fourlines == NULL ){      /* check does 4 lines file exist etc */
    perror ("Error opening 4 lines file");
    fourlineslineNum = -1; /* use this as a file not found code */
} else {
    // fgets returns NULL when it gets to the end of the file
    while ( fgets(fourlinesArr[fourlineslineNum], sizeof(fourlinesArr[fourlineslineNum]), fourlines ) != NULL ) {

        fourlineslineNum++;
    }
    fclose (fourlines);
}
//end of fileIO.c code


//testing
char name[20] = "Fabantou";
printf("%s\n", namesArr[62]);
printf("%s\n", fourlinesArr[0]);

if(strstr(fourlinesArr[0], namesArr[62]) != NULL) {
    printf("Success\n");
}
else {
    printf("Failure\n");
}

if(strstr(fourlinesArr[0], name) != NULL) {
    printf("Success\n");
}
else {
    printf("Failure\n");
}

return 0;
}

0 个答案:

没有答案