【问题标题】:i have a program that takes input a string that's called search which is the target and i want to search in the csv file if the "search" is there我有一个程序,它输入一个称为搜索的字符串,它是目标,如果“搜索”存在,我想在 csv 文件中搜索
【发布时间】:2021-07-19 07:42:04
【问题描述】:
#include <stdio.h>
#include <string.h>

void myFgets(char str[], int n);

int main(int argc, char** argv) 
{
    if (argc < 2)
    {
        printf("Usage: csv <csv file path>\n");
        return 1;
    }
    else
    {
        char ch = ' ', search[100], dh = ' ';
        int row = 1;
        printf("Enter value to search: ");
        myFgets(search, 100);

        FILE* fileRead = fopen(argv[1], "r");

        if (fileRead == NULL)
        {
            printf("Error opening the file!\n");
            return 1;
        }

        while ((ch = (char)fgetc(fileRead)) != EOF)
        {
            char str[100];
            int i = 0, pos = ftell(fileRead);
            while ((dh = (char)fgetc(fileRead)) != ',')
            {
                str[i] = dh;
                i++;
            }
            fseek(fileRead, pos + 1, SEEK_SET);
            if (strstr("\n", str) != NULL)
            {
                row++;
            }
            if (strstr(search, str) != NULL)
            {
                printf("Value was found in row: %d\n", row);
                break;
            }
        }
    }

    getchar();
    return 0;
}

/*
Function will perform the fgets command and also remove the newline
that might be at the end of the string - a known issue with fgets.
input: the buffer to read into, the number of chars to read
*/
void myFgets(char* str, int n)
{
    fgets(str, n, stdin);
    str[strcspn(str, "\n")] = 0;
}

在第 39 行中,我遇到了一个错误,但我不知道为什么看起来我做的一切都很好 我试图遍历行并用','分割它们,所以我可以检查 search == 是否对它,但它不是 wokring 我使用函数 strstr 来比较 2 个字符串,它工作正常,除了唯一的问题是在 dh 我在 dh 之后做了 fseek,所以我不会在 ch 循环中写错地方

【问题讨论】:

  • 您的第一步是弄清楚您是在编写 C 代码还是 C++ 代码。它们是两种完全不同的语言。您打算编写 C 程序还是 C++ 程序?

标签: c++ c csv file fopen


【解决方案1】:

你忘记终止字符串了。

while ((dh = (char)fgetc(fileRead)) != ',')
{
    str[i] = dh;
    i++;
}
str[i] = '\0'; /* add this to terminate the string */

另外看起来if (strstr(search, str) != NULL) 应该是if (strstr(str, search) != NULL) 从文件内容中搜索要搜索的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多