我遇到了在 C 中工作的分段错误的问题,我无法弄清楚为什么会发生这种情况。我认为这与滥用 fget(c) 函数有关。
while((ch = fgetc(fp))!= EOF) {
printf("Got inside first while: character is currently %c \n",ch); //**********DELETE
while(ch != '\n') {
char word[16]; //Clear out word before beginning
i = i+1; //Keeps track of the current run thru of the loop so we know what input we're looking at.
while(ch != ' ') {
printf("%c ",ch); //**********DELETE
//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';
printf("%s",word);
ch = fgetc(fp);
}
//The following if-else block sets the variables TextA, TextB, and TextC to the appropriate Supply Types from the input.
//This part may be confusing to read mentally, but not to trace. All it does is logically set TextA, B, and C to the 3 different possible values SupplyType.
if(word!=TextB && word!=TextC && i==1 && TextB!="") {
strcpy(TextA,word);
}
else if(word!=TextA && word!=TextC && i==1 && TextC!="") {
strcpy(TextB,word);
}
else if(word!=TextB && word!=TextA && i==1) {
strcpy(TextC,word);
}
switch(i) {
case 1:
if(TextA == word) {
SubTypeOption = 1;
}
else if(TextB == word) {
SubTypeOption = 2;
}
else if(TextC == word) {
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(i)
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)
使用gdb(只是a.out的简单运行)我发现问题与 getc 有关,但它不知道哪一行/哪一行。但是,我的程序确实输出“第一次进入一边:字符当前是 S”。这个 S 是我输入文件中的第一个字母,所以我知道它在某种程度上是按应有的方式工作的,但随后会导致段错误。
有没有人对可能出现的问题或如何调试此问题有任何建议?我对 C 语言比较陌生,主要对语法感到困惑。我有一种感觉,我做了一些小的语法错误。
顺便说一句,这段代码是为了从字符串中获取一个单词。示例:请帮我完成这个程序
应该给出等于“帮助”的词
更新:现在伙计们,我遇到了一个很酷的错误(虽然很神秘)。当我重新编译时,我得到了这样的东西:
单词现在是 w S 单词现在是 w Su 单词现在是 w Sup ... 等等,除了它会持续一段时间,建立一个单词金字塔。
我的输入文件中只有字符串“SupplyTypeA 1.23 1 1.65 1”。
更新:分段错误已修复(问题是,我使用 fgetc() 超出了文件末尾)。感谢大家。
如果有人仍然看这个,他们能帮我弄清楚为什么我的输出文件不包含它应该包含的任何正确数字吗?我想我可能在我得到的词上滥用了 atof 和 atoi 。