【问题标题】:Jumble solving program crashes on run混乱解决程序在运行时崩溃
【发布时间】:2012-04-22 00:38:49
【问题描述】:

我正在为我的 C 入门课程编写一个程序,该程序要求我根据我教授的字典文本文件编写一个程序来解决混乱的谜题(你知道,你在报纸上看到的那些字谜谜题)给我们。它将字典中的单词按字母顺序排列,从文本文件(称为“jumble.txt”)中获取混乱,按字母顺序排列,然后运行字符串比较以找到匹配项。我已经编写了所有代码,但是当我尝试运行它时它立即崩溃,我不知道为什么。我想也许 Stackoverflow 用户可以在这里帮助我。

这是我的代码:

#include <stdio.h>
#include <strings.h>
#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000

typedef struct {
    char word[MAX_WORD_LEN+1];
    char sort[MAX_WORD_LEN+1];
} jumble_type;

void bubblesort(char letters[], int length);


int main () {
    int words, jumbles;
    int j, q;
    jumble_type list[MAX_NUM_WORDS];
    jumble_type list2[MAX_NUM_WORDS];


// Creating file pointers
FILE *ifp;
FILE *ifp2;

//Opens Jumble and dictionary files and reads the info from them
ifp = fopen("jumbledct.txt", "r");
ifp2 = fopen("jumble.txt", "r");

//Assigns the value of "words" to the first line of jumbledct.txt
fscanf(ifp, "%d", words);

//Assigns the value of "jumbles" to the first line of jumble.txt
fscanf(ifp2, "%d", jumbles);

// Reads the words from the dictionary into the "word" section of our
// list structure.
int i;
for (i = 0; i < words; i++){
    fscanf(ifp, "%s", &list[i].word);
    strcpy(list[i].sort, list[i].word);
    bubblesort(list[i].sort, strlen(list[i].sort));
    printf("%s\n", list[i].sort);
    }

//Reads from Jumble.txt
for (i = 0; i < jumbles; i++){
    fscanf (ifp2, "%s", &list2[i].word);
    strcpy(list2[i].sort, list2[i].word);
    bubblesort(list2[i].sort, strlen(list2[i].sort));
    //printf("%s\n", list2[i].sort);
    }

for(j=0;j<jumbles; j++){
        printf("JUMBLE PUZZLE # %d: %s\n", j+1, list2[j].word);


    int x=0;

for (q = 0; q < words; q++){



        if(strcmp(list2[j].sort, list[q].sort)==0){

            printf("%s\n", list[q].word);
            x++;
        }
}
 if (x == 0){
            printf("Sorry, this puzzle has no solutions. \n\n");
        }
        printf("\n");

}


return 0;
}

void bubblesort(char letters[], int length) {
char temp;
    int x, y;
    for(x = 0; x < length; x++){
        for (y = x; y < length; y++){
            if (letters[x] > letters[y]){
                temp = letters[y];
                letters[y] = letters[x];
            letters[x] = temp;
        }
    }
}
}

提前感谢您的帮助。

【问题讨论】:

  • 使用调试器(甚至添加一些 printfs)来了解崩溃的位置。
  • 您的 cmets 已关闭;您将在jumbledct.txt 中可以扫描的任何int 分配给words,而不是相反。 (或者,他们可以阅读“将“单词”的名称分配给...')另外,@Nick Atoms 是正确的:您需要传递 *scanf 指针。

标签: c arrays struct io


【解决方案1】:

我的 C 有点生疏了,但 fscanf 函数的第三个参数不应该是地址(如 &words 和 &jumbles)吗?

【讨论】:

  • 就是这样,我现在觉得自己非常愚蠢。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2010-10-28
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多