经过不懈地寻找解释之后,我决定在stackoverflow上问一些大师。因此,我目前正在尝试从名为data.txt的文件中逐行读取每个输入。该程序使用简单的scanf等可以完美运行,但是当我想从文件中读取输入值时,该程序仅读取txt的前三行,并且在无限循环中不断重复。我的代码如下所示。我保留了大部分代码,以防其他人想使用它。程序将无限读取1、12、0。示例data.txt文件如下所示
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// Global variables
char *Hstring = NULL;
int maxLength, parity;
char *temp = NULL;
int userChoice = 0;
void option1() {
// User inputs length and even or odd parity bit
printf("\n*** Maximum Code Length: %d", maxLength);
//scanf("%d",&maxLength);
printf("\n*** Parity: %d", parity);
//scanf("%d",&parity);
// allocate memory for hamming string based on maximum length and
//size of character element
Hstring = (char *)malloc(maxLength * sizeof(char));
return;
}
void option2() {
/* declare local vars */
int aLength, k, parBits, parValue, errorPos, i, j;
/* prompt for hamming code as a "string"*/
printf("\nEnter the Hamming Code: ");
scanf("%s", Hstring);
temp = Hstring;
aLength = strlen(Hstring);
parBits = ceil(log(aLength) / log(2));
}
int main() {
FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("ERROR OPENING THE FILE\n");
}
fscanf(fp, "%d %d %d", &userChoice, &maxLength, &parity);
//end file open
while (userChoice != 3) {
printf("\nEnter Selection: %d", userChoice);
//scanf("%d",&userChoice);
switch (userChoice) {
case 1:option1();
break;
case 2:option2();
break;
case 3:
printf("\n*** Program Terminated Normally\n");
break;
default: printf("invalid input please input another number\n\n");
break;
}
}
/* print out menu, prompt for choice, and call appropriate procedure
until user quits */
return 1;
}
SAMPLE data.txt
1
12
0
2
1000
1
代码在读取option1()中的第三个整数(奇偶校验)时开始循环
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
您永远不会在while循环中修改userChoice
,因此它将永远循环。
无论如何,即使您在while循环中使用了fscanf
,因此读取了整个文件,直到找到userChoice == 3
,也要让循环终止条件仅取决于内容是一个坏主意对于文件,您还应该检查fscanf
的结果以确认文件是否终止。您的示例数据仍将永远循环,因为其中不包含3
。
答案 1 :(得分:0)
https://stackoverflow.com/a/53475412/4386427的答案正确地描述了问题,即您有一个无限循环,因为userChoice
仅被读取了一次。
这里是修复建议。
int main() {
FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("ERROR OPENING THE FILE\n");
}
while (userChoice != 3) {
// Check that exactly 3 items are read from the file.
// If not terminate the program
if (fscanf(fp, "%d %d %d", &userChoice, &maxLength, &parity) != 3) {
printf("Illegal input from file or EOF. Terminating program\n");
break;
}
switch (userChoice) {
case 1:option1();
break;
case 2:option2();
break;
case 3:
printf("\n*** Program Terminated Normally\n");
break;
default: printf("invalid input please input another number\n\n");
break;
}
}
return 1;
}