c - 读取具有多个条件的数据时如何将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;
}
解决方案
如果我正确阅读了您的问题,您想从其余处理中提取文件迭代逻辑。
可以让您获得此功能的基本更改很简单:
#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
全局变量设为一个特别危险的坏主意。
推荐阅读
- html - 在 TYPO3 中预加载脚本或 CSS
- azure-devops - 不同 Git 存储库中的源代码和 YAML 文件
- flutter - 颤振升级后如何修复“发现重复类”错误?
- intellij-idea - 重置 Intellij / DataGrip 2020.1 字体更改
- php - 使用 Ajax 添加和删除 SQL
- postgresql - org.hibernate.type.SerializationException:无法反序列化错误,使用 CriteriaBuilder API 从 postgreSQL 读取 json 字段
- ios - 作为开发人员需要在 iOS13 SDK 的代码库中进行哪些更改
- ios - 是否可以多次触发推送通知的 requestAuthorization 系统对话框
- http - 如何在golang中为请求和重定向添加值
- image - 根据条件更改图像