简体   繁体   English

带用户输入的struct数组中的strstr char数组

[英]strstr char array inside struct array with user input

Can someone tell me why p is always NULL even if strstr correctly found (in search function)? 有人可以告诉我为什么即使正确找到了strstr(在搜索功能中)p总是为NULL? I'm filling struct array from file. 我从文件填充结构数组。 Sorry for re-post of this other question but none of them are helped. 很抱歉重新发布另一个问题,但没有一个人得到帮助。

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

struct player {

    int no, age;

    char name[20];  

} players[20];

void fillstruct(char *);
void search(char []);

int main(int argc, char *argv[])
{
    int arg;
    int c;        
    int d;           
    int i=0;        

    char a[100];
    char *filename = NULL;

    while((arg=getopt(argc, argv, "f:"))!=-1)
    {
        switch(arg)
        {
            case 'f':
                filename = optarg;
                fillstruct(filename);
                break;
            default:
                break;
        }
    }   
    while((c=fgetc(stdin))!=EOF)
    {
        if(c!=10)
        {
            a[i]=c;
            i++;
        }       
        else
        {
            a[i]='\0';
            search(a);      
            i=0;            
        }       
    }
    return 0;
}

void search(char a[])
{
    int i=0;
    int col;
    int found=0;
    char *p =NULL;
    while((i<20)&&(found==0))
    {
        p = strstr(a, players[i].name);
        if(p)
        {
            col = p-a;
            printf("\nPlayer '%s' found in '%s'.. Found index: %d", a, players[i].name, col);
            found=1;
        }   
        else
        {
            printf("\np=%s a=%s player[%d].name=%s", p, a, i, players[i].name);
        }
        i++;
    }   
}

void fillstruct(char *name)
{
    FILE *fp;
    char line[100];
    int i=0;

    fp = fopen(name, "r");
    if(fp==NULL)
    {   
        exit(1);
    }

    while(fgets(line, 100, fp)!=NULL)
    {
        players[i].no=i;
        strcpy(players[i].name, line);
fprintf(stdout, "\nplayer=%s", players[i].name);
        players[i].age=20;
        i++;
    }   
    fclose(fp); 
}

fgets stores the \\n and then stops taking input. fgets存储\\n ,然后停止接受输入。

So suppose a player name is "user" , players[i].name will be equal to "user\\n" while a is "user" . 因此,假设玩家名称为"user"players[i].name将等于"user\\n"a"user"

So return of strstr is always NULL . 因此, strstr返回始终为NULL

Try this instead: 尝试以下方法:

p = strstr(players[i].name,a);

OR, remove the \\n after taking input from file by fgets : 或者,通过fgets从文件中输入后,删除\\n

while(fgets(line, 100, fp)!=NULL)
{
    players[i].no=i;
    strcpy(players[i].name, line);
    players[i].name[strlen(players[i].name)-1]='\0'; //add this line
    fprintf(stdout, "\nplayer=%s", players[i].name);
    players[i].age=20;
    i++;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM