Strange counter variable in C inside loops, not changing back -
pay attending counter variable. notice how set 0 above sec while loop. reason, printf(counter) statement says counter never gets reset zero. continues ++ing through end of file. totally messes logic program. help?
ch=fgetc(fp); while(ch != eof) { counter = 0; while(ch != '\n' && ch!=eof) { char word[32] = ""; // keeps track of current run thru of // loop know input we're looking at. counter = counter+1; while(ch != ' ' && ch!='\n' && ch!=eof) { // next block builds character // array current "word" (separated // spaces) in input file. int len = strlen(word); word[len] = ch; word[len+1] = '\0'; ch = fgetc(fp); } // next if-else block sets variables // texta, textb, , textc appropriate supply types. // part may confusing read mentally, not // trace; logically set texta, b, , 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: // don't need maintain track of // product's name, nil case i=2. // included 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 next if-else block "tallys up" total amounts of subtypes bought , sold 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)
some thoughts:
what type of ch
? should int
. (note fgetc
returns int
). if char
look ch != eof
may not work expect to.
if input has more 16 characters, can see counter
beingness reset. depends on exact code compiler has generated, if store @ word[16]
(the seventeenth byte) , counter
on stack after word
, start writing characters memory contains counter
.
c counter
No comments:
Post a Comment