我正在尝试解析文件每一行中的每个标记。但是我在内部while循环中遇到了无限循环。为什么是这样?这不是因为条件为“ true”,因为我在while循环中有break语句。我认为我不正确检查何时到达行尾。char currentLine[MAXIMUM_LINE_LENGTH + 1]; // + 1 for terminating char while (true) { if (fgets(currentLine, MAXIMUM_LINE_LENGTH, inputFilePointer) == EOF ) { break; } else { // we need to parse the currentLine // check if the currentLine is too long if (strlen(currentLine) > MAXIMUM_LINE_LENGTH) { // print to the file that the currentLine being parsed it too long printf( "WARNING: currentLine is too long and must be <= 256 characters\n"); continue; // move on to next line in input file } else { // currentLine has valid length while (true) { // iterate through each token within the currentLine and parse the token char *currentToken = strtok(currentLine, " $,\t"); printf("currentToken = %s", currentToken); // do something with currentToken if (currentToken == NULL || *currentToken == '#') { break; // <== ERROR This break statement is never getting hit WHY? } } } } } 最佳答案 几点:如果将MAXIMUM_LINE_LENGTH定义为常量,则WARNING消息应真正引用它,而不是硬编码值256。但这不是实际的问题。该代码需要char currentLine[MAXIMUM_LINE_LENGTH + 1]; // + 1 for terminating charwhile (true) { if (fgets(currentLine, MAXIMUM_LINE_LENGTH, inputFilePointer) == EOF ) { break; } else { // we need to parse the currentLine // check if the currentLine is too long if (strlen(currentLine) > MAXIMUM_LINE_LENGTH) { // print to the file that the currentLine being parsed it too long printf( "WARNING: currentLine is too long and must be <= 256 characters\n"); continue; // move on to next line in input file } else { // currentLine has valid length char *currentToken = strtok(currentLine, " $,\t"); while(currentToken != NULL && *currentToken != '#') { // iterate through each token within the currentLine and parse the token printf("currentToken = %s", currentToken); // do something with currentToken currentToken = strtok(NULL, " $,\t"); // get next token } } }}到底是怎么回事? strtok函数实际上“记住”了您所要求的字符串,并在找到令牌的位置放置了一个nul字符。下次调用它时,它将在“下一个点”开始,并扫描下一个标记。因此,它实际上会覆盖您的初始字符串,并缓慢地“ chomps”它。在原始代码中,您一直在向strtok传递“新”字符串,因此它永远不会超过第一个标记。需要将其传递给NULL,以使其保持同步(如上例所示)。还要注意,我使用了这样一个事实,即我们需要对strtok进行调用的两个版本来稍微清理代码的结构-现在while的条件是终止条件(因为第一次调用在进入while循环之前发生)。 09-04 04:23