注意我的计数器变量。注意我是如何在第二个while循环之上将它设置为0。出于某种原因,我的printf(计数器)语句表明计数器永远不会重置为零。它只是继续整个文件的结尾。这完全扰乱了我对这个程序的逻辑。有什么帮助吗?
ch=fgetc(fp);
while(ch != EOF)
{
counter = 0;
while(ch != '\n' && ch!=EOF)
{
char word[32] = "";
// keeps track of the current run thru of the
// loop so we know what input we're looking at.
counter = counter+1;
while(ch != ' ' && ch!='\n' && ch!=EOF)
{
// the following block builds up a character
// array from the current "word" (separated
// by spaces) in the input file.
int len = strlen(word);
word[len] = ch;
word[len+1] = '\0';
ch = fgetc(fp);
}
// the following if-else block sets the variables
// TextA, TextB, and TextC to the appropriate Supply Types.
// this part may be confusing to read mentally, but not to
// trace; all it does is logically set TextA, B, and C.
if(counter==1)
{
if(strlen(TextA)==0)
{
strcpy(TextA,word);
}
else if(strlen(TextB)==0 && strcmp(word,TextA)!=0 && strcmp(word,TextC)!=0)
{
strcpy(TextB,word);
}
else if(strlen(TextC)==0 && strcmp(word,TextA)!=0 && strcmp(word,TextB)!=0)
{
strcpy(TextC,word);
}
}
printf("TextA: %s, TextB: %s, TextC: %s word: %s \n",TextA,TextB,TextC,word);
printf("i equals: %d",counter);
switch(counter)
{
case 1:
printf("Got in case 1.");
if(strcmp(TextA,word)==0)
{
SubTypeOption = 1;
}
else if(strcmp(TextB,word)==0)
{
SubTypeOption = 2;
}
else if(strcmp(TextC,word)==0)
{
SubTypeOption = 3;
}
break;
case 2:
// We actually ultimately don't need to keep track of
// the product's name, so we do nothing for case i=2.
// Included for readibility.
break;
case 3:
WholesalePrice = atof(word);
break;
case 4:
WholesaleAmount = atoi(word);
break;
case 5:
RetailPrice = atof(word);
break;
case 6:
RetailAmount = atoi(word);
break;
} //End switch(counter)
if(ch='\n')
counter = 0;
ch = fgetc(fp);
}//End while(ch != '\n')
//The following if-else block "tallys up" the total amounts of SubTypes bought and sold by the owner.
if(SubTypeOption == 1)
{
SubType1OwnersCost = SubType1OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType1ConsumersCost = SubType1ConsumersCost + (RetailPrice *(float)RetailAmount);
}
else if(SubTypeOption == 2)
{
SubType2OwnersCost = SubType2OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType2ConsumersCost = SubType2ConsumersCost + (RetailPrice *(float)RetailAmount);
}
else if(SubTypeOption == 3)
{
SubType3OwnersCost = SubType3OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType3ConsumersCost = SubType3ConsumersCost + (RetailPrice *(float)RetailAmount);
}
}//End while((ch = fgetc(fp))!= EOF)
答案 0 :(得分:3)
一些想法:
ch
的类型是什么?它应该是int
。 (请注意,fgetc
会返回int
)。如果是char
,则表达式ch != EOF
可能无法按预期运行。
如果输入的字符数超过16个,我很快就会看到counter
被重置。这取决于您的编译器生成的确切代码,但是如果您在word[16]
(第17个字节)处存储了某些内容并且counter
紧跟在word
之后的堆栈中,那么您将开始编写字符进入包含counter
。