首页 > 解决方案 > 读取具有多个条件的数据时如何将while循环保留在函数中?

问题描述

这段代码给了我特殊的数据,因为我使用了!pinFound. 所以我希望它能让细节处于一个状态。这意味着,如果我想要pinFound结果,那么它应该只给我pinFound结果,或者如果我想要!pinFound结果,那么它应该只给我!pinFound结果。

我不希望同时打印两个结果 另外我有多个函数可以从中读取数据。所以我不想在 main 函数中一次又一次地重复 while(fgets(...)) 。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_LEN 200

int i;
char line[STRING_LEN], *lineOne = NULL, *numbers[5], pinFind[STRING_LEN], *pinFound = NULL;  
int find(FILE * fname, char *findPin){
    while(fgets(line, STRING_LEN, fname)){  
        lineOne = strtok(line, "\n");
        numbers[0] = strtok(lineOne, ",");
        for(i = 1; i < 5; i++)
            numbers[i] = strtok(NULL, ",");
        pinFound = strstr(numbers[2], findPin);
        if(!pinFound)
            return line;    
    }
}

int main(){
    FILE * fp1 = fopen("file.csv", "r");
    printf("Enter the pin code: ");
    scanf("%s", pinFind);

    find(fp1, pinFind);
    for(i=0; i<5; i++)
        printf("%s\n", numbers[i]);

    return 0;
}

标签: cwhile-loopconditional-statements

解决方案


如果我正确阅读了您的问题,您想从其余处理中提取文件迭代逻辑。

可以让您获得此功能的基本更改很简单:

#include <stdbool.h>

// parse next line, return true if line was parsed
bool nextLine(FILE * fname, char *findPin)
{
    if (fgets(line, STRING_LEN, fname))
    {
        lineOne = strtok(line, "\n");
        numbers[0] = strtok(lineOne, ",");
        for (int i = 1; i < 5; i++)
            numbers[i] = strtok(NULL, ",");
        pinFound = strstr(numbers[2], findPin);
        return true;
    }
    else
    {
        return false;
    }
}

然后主要是:

FILE * fp1 = fopen("file.csv", "r");

printf("Enter the pin code: ");
scanf("%s", pinFind);

while (nextLine(fp1, pinFind))
{
    // if you are here, line was parsed, so
    // check the value of 'pinFound'

    if (pinFound)
        doSomething(numbers);
    else
        doSomethingElse(numbers);
}

fclose(fp1);

对于一个家庭作业项目,这或多或少应该可以解决问题,但我建议将nextLine调用之间的状态封装在一个单独的结构中,而不是保持全局。将所有这些变量设为全局变量是个坏主意,但将i全局变量设为一个特别危险的坏主意


推荐阅读