繁体   English   中英

C 从文本文件中检查字符串

[英]C check string's from a text file

我是 c 的新手,我正在编写一个从用户那里获取字符串并将其与文本文件中的字符串进行比较的代码,并且我的代码仅在我比较两个字符时才有效,当我比较两个字符串时它不起作用如果有人知道我该如何解决这个问题,那将非常有帮助。 比较行在 searchFile function 中。 文本文件是一个 csv 文件,因此我需要将 char 与 string 进行比较,然后将其与 string_to_search 进行比较。 代码末尾的 csv 文件示例

示例:要搜索的字符串 = 'c' 起作用,要搜索的字符串 'name' 不起作用

#include <stdio.h>
#define STR_LEN 100

int searchFile(char* string_to_search, char* path);

int main(int argc, char* argv[])
{
    FILE* text_file = 0;
    int found = 0, choice = 0;
    char string_to_search[STR_LEN] = {0};
    if (!(fopen(argv[1], "r") == NULL)) //check if file exists
    {
        do 
        {
            printf("Please enter your choice:\n");
            printf("1 - Search a term in the document.\n");
            printf("2 - change a value in a specific place.\n");
            printf("3 - copy a value from one place to another\n");
            printf("4 - Exit\n");
            scanf("%d", &choice);
            getchar();
            switch (choice)
            {
                case 1:
                    fgets(string_to_search, STR_LEN, stdin);
                    string_to_search[strcspn(string_to_search, "\n")] = 0;
                    found = searchFile(string_to_search, argv[1]); //found = where the string line
                    if (found != 0)
                        printf("Value was found in row %d\n", found);
                    else
                        printf("Value Wasn't Found\n");
            }
        }while(choice != 4);
    }
    else
    {
        printf("file does not exists\n");
    }
    getchar();
    return 0;
}
int searchFile(char* string_to_search, char* path)
{
    FILE* file = fopen(path, "r");
    char ch = ' ';
    int i = 0, len = 0, count = 1;
    fseek(file, 0, SEEK_END);
    len = ftell(file);
    fseek(file, 0, SEEK_SET);
    len = len - 2;
    char* string = (char*)malloc(sizeof(char) * len);
    do //copying the chars to a string
    {
        ch = fgetc(file);
        string[i] = ch;
        i++;
    } while (ch != EOF);
    fclose(file);
    for (i = 0; i < len; i++)
    {
        if (string[i] == *string_to_search) //the compare
        {
            free(string);
            return count;
        }
        if (string[i] == '\n')
        {
            count++;
        }
    }
    free(string);
    return 0;
}

CSV 文件的示例:

roee,itay,3,4
5,6,7,8
a,b,c,d
e,f,g,h

您必须更改以下行:

if (string[i] == *string_to_search) //the compare

进入

if (string[i] == string_to_search[i]) //the compare

问题是*string_to_search总是指string_to_search的第一个字符。 使用[i]您将获得字符串的第 n 个字符,就像您对变量string所做的那样。 所以你注意到它适用于两个字符的比较,但不适用于两个字符串,因为在一个字符串上你总是会与string_to_search的第一个字符进行比较。 例如,如果您想比较"aaa" ,它也可以。

但正如评论部分所述,您可能还想使用strcmp()而不是循环。 在那里你还必须传递string_to_search而不是*string_to_search ,因为你想传递指向字符串的指针而不是单个字符。

暂无
暂无

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

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