【发布时间】:2017-12-14 00:01:08
【问题描述】:
最终目标是从文件中创建一个字符串数组。所以我有一个文件,我需要从 temp1、temp2、temp3 等获取临时变量。我不知道提前有多少。我的第一个想法是从我使用 strcat 找到的变量创建一个普通字符串,然后使用标记拆分它。我想我可以通过正常添加字符串来绕过这个。
while(feof(inputFile))
{
fscanf(inputFile, " %s ", readIn);
if(strcmp("AND", readIn) == 0 || strcmp("OR", readIn) == 0 || strcmp("NAND", readIn) == 0 || strcmp("NOR", readIn) == 0 || strcmp("XOR", readIn) == 0)
{
fscanf(inputFile, "%s ", readIn);
fscanf(inputFile, "%s ", readIn);
fscanf(inputFile, "%s ", tempVar);
//printf("the char is %c", tempVar[0]);
//check to see if its a temp variable since temps are always lower case
if(tempVar[0] == 't')
{
numVars++;
tempHeaders = realloc(tempHeaders, sizeof(char*) * numVars);
int temp = numVars -1;
printf("the variable is %s and the number is %d\n", tempVar, temp);
tempHeaders[numVars - 1] = tempVar;
}
numGates++;
}
}
此时变量的数量是对的,问题是添加到数组 tempHeaders 时。数组的整个值将是文件的最后一个单词,即如果最后一个单词出现了。 tempHeaders i - n 将全部消失。有任何想法吗?谢谢
我已经从 while 循环中删除了 feof 并更改为 "while(fscanf(inputFile, "%s ", readIn) != EOF){"
样本输入将是
OR IN1 IN2 temp1
OR IN3 IN4 temp2
OR IN5 IN6 temp3
OR IN7 IN8 temp4
AND temp1 temp2 temp5
AND temp3 temp4 temp6
XOR temp2 temp6 OUT1
此时的样本输出
the variable is temp1 and the number is 0
the variable is temp2 and the number is 1
the variable is temp3 and the number is 2
the variable is temp4 and the number is 3
the variable is temp5 and the number is 4
the variable is temp6 and the number is 5
Printing OUT1
Printing OUT1
Printing OUT1
Printing OUT1
Printing OUT1
Printing OUT1
numGates = 7, numVars = 6
打印应该是 temp1、temp2、temp3 等...
【问题讨论】:
-
我知道 feof 经历了额外的时间,但它不应该添加到数组中的条件?另外,我将如何在我的代码中使用它,我可以这样做 (fgets(readIn, 5000, inputFile) != NULL) 会改变我在这里所做的正常 fscanf 值吗?
-
1.检查来自
fscanf的返回值 2. 使用正确的格式说明符以确保没有缓冲区溢出 -
3) 在你知道它的作用之前不要使用 feof()。
-
@wildplasser - 也就是我的第一条评论
标签: c