简体   繁体   English

C Strncmp返回部分输入

[英]C Strncmp Return Partial Input

I currently have a linked list structure running and I need to find a way to let a user search the struct for a certain field. 我目前正在运行一个链表结构,我需要找到一种方法让用户在结构中搜索特定字段。 I have this done, but the problem is it must be exact. 我已经完成了,但是问题是它必须准确。 For example, if the user enters "maggie" it will return the result, but if the user types in "mag" it will not return the maggie record like I want. 例如,如果用户输入“ maggie”,它将返回结果,但是如果用户键入“ mag”,它将不会像我想要的那样返回maggie记录。

int counter = 0;
char search[MAX];
record_type *current = head;

printf("\n\n- - - > Search Records\n\n");
printf("\tSearch: ");
scanf("%s", search);

/* search till end of nodes */
while(current != (record_type*) NULL) {
    if(strncmp(current->name, search, MAX) == 0) {
        printf("\t%i. %s", counter, current->name);
        printf("\t%u", current->telephone);
        printf("\t%s\n", current->address);
        counter++;
    }
    current = current->next;
}

Any ideas? 有任何想法吗? I'm guessing there is a way to just compare with chars? 我猜有一种方法可以与字符进行比较吗? Thanks! 谢谢!

You're question isn't entirely clear... 您的问题尚不完全清楚...

If you only want to return exact matches, use strcmp instead 如果只想返回完全匹配项,请改用strcmp

if (strcmp(current->name, search) == 0) {

If you want to return partial matches, use strncmp but over a size that matches your search string: 如果要返回部分匹配项,请使用strncmp但其大小应与搜索字符串匹配:

if (strncmp(current->name, search, strlen(search)) == 0) {

代替strncmp(current->name, search, MAX)使用strncmp(current->name, search, strlen(search))或使用strstr函数。

strncmp compares the number of characters to compare. strncmp比较要比较的字符数。 So don't compare that many. 所以不要比较那么多。

Start by comparing the string length, or just use strcmp() . 首先比较字符串长度,或者只使用strcmp()

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

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