目标:如何成功实现EOF来停止无限循环?
调用函数的部分:
do {
pId = readInputField(fptr, DELIMITER_SPACE);
pName = readInputField(fptr, DELIMITER_SEMICOLON);
pDob = readInputField(fptr, DELIMITER_SPACE);
pHobbyList = readInputField(fptr, DELIMITER_NEWLINE);
} while (NULL != pId
&& NULL != pName
&& NULL != pDob
&& NULL != pHobbyList);
函数定义:
char* readInputField(FILE* fPtr, const char delimiter) {
int numCharRead;
char bufferString[MAX_LENGTH_INPUT];
char *pBufferString;
numCharRead = 0;
// flush: if spaces are found
' ' == (bufferString[numCharRead] = fgetc(fPtr)) ? 0 : numCharRead++;
// get chracter array before delimiter
while (delimiter != bufferString[numCharRead - 1]
&& numCharRead < MAX_LENGTH_INPUT) {
bufferString[numCharRead++] = fgetc(fPtr);
}
// exclude delimiter from the string
bufferString[numCharRead - 1] = '\0';
printf("numCharRead= \"%d\"\n", numCharRead);
printf("delimiter: \"%c\"\n", delimiter);
printf("bufferString: \"%s\"\n", bufferString);
pBufferString = malloc(sizeof(char*) * strlen(bufferString));
/* deleted:
pBufferString = bufferString;
return EOF == bufferString[numCharRead - 1] ? NULL : pBufferString;
*/
}
样本输入:
VIC Lee, Victoria; 02/25/90 Knitting;Photography;Dance;
样本输出:
numCharRead= "4"
delimiter: " "
bufferString: "VIC"
numCharRead= "14"
delimiter: ";"
bufferString: "Lee, Victoria"
numCharRead= "9"
delimiter: " "
bufferString: "02/25/90"
numCharRead= "28"
delimiter: "
"
bufferString: "Knitting;Photography;Dance;"
// after this, infinite loop begins with garbage data
我的电话是查看上面的 return 语句。由于某种原因,它不会检测它是否是 EOF。
任何帮助表示赞赏!谢谢!
更新: 感谢@JoachimPileborg!我在下面更新了我的代码:
// check for EOF
if(bufferString[numCharRead-1] == EOF) {
return NULL;
} else {
pBufferString = malloc(sizeof(char*));
strcpy(pBufferString, bufferString);
return pBufferString;
}