[英]How to keep the while loop in a function when reading data with multiple conditions?
這段代碼給了我特殊的數據,因為我使用了!pinFound
。 所以我希望它讓細節處於一種狀態。 這意味着,如果我想要pinFound
結果,那么它應該只給我pinFound
結果,或者如果我想要!pinFound
結果,那么它應該只給我!pinFound
結果。
我不希望同時打印兩個結果另外我有多個函數可以從中讀取數據。 所以我不想在主函數中一次又一次地重復 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
全局變量是一個特別危險的壞主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.