4

我在学习 C 时一直在疯狂地研究。我一直在调试 C 程序,我认为我在这里遇到了一些重大问题。现在我有关键问题。我制作了一个虚拟程序,在一个语句中打印两个字符串,如下所示:

   #include<stdio.h>

int main(int argc, char* argv[])
{
    char *herp = "Derp";
    char *derp = "Herp";

    printf("Herp %s Derp %s\n", herp, derp);

    return 0;
}

这按预期打印出来。我明白了

Herp Derp Derp Herp

所以,我想,让我通过做类似的事情来调试我自己的程序。我的程序中的以下行

printf("word is: %s and jumbled word is: %s\n", word, jumbleWord);

应该打印出类似的东西

Word is: word and jumbled word is: dowr

但它会打印出类似的东西

and jumbled word is: dowr

输出的第一部分去哪儿了?我需要能够在同一行上打印它们以进行调试。此外,像这样的声明不起作用的事实告诉我,正在发生非常奇怪的事情,我因为扯掉头发而秃顶。正如我链接的帖子所表明的那样,我最终想比较这些字符串值,但是如果 printf() 不能正常工作,我怎么能这样做呢?

我在下面发布了整个程序,这样你就可以看到一切发生的地方。我只是在学习如何使用指针。当我想弄乱一个单词时,我最初有两个指针指向同一个内存,但效果不太好!所以我解决了这个问题,得到了两个单独的内存空间,里面有我需要的单词。现在,我只是无法打印它们。鉴于以下代码,这一切都说得通:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX_WORD_LENGTH 25

//Define global variables 
int numWords; 

//Preprocessed Functions 
void jumblegame();
void readFile(char *[]);
void jumbleWord(char *);
void guess(char *,char *); 

int main(int argc, char* argv[])
{
    jumblegame();
    return 0;
}

void jumblegame()
{
    //Load File 
        int x = 5050; //Rows
        char *words[x];
        readFile(words);

    //Define score variables 
        int totalScore = 0;
        int currentScore = 0; 

   //Repeatedly pick a random work, randomly jumble it, and let the user guess what it is
         srand((unsigned int)time(NULL));
         int randomNum = rand() % numWords + 1;

         char source[MAX_WORD_LENGTH + 1];
         char jumble[MAX_WORD_LENGTH + 1];

         strncpy(source, words[randomNum], MAX_WORD_LENGTH + 1);
         strncpy(jumble, words[randomNum],MAX_WORD_LENGTH + 1);

         jumbleWord(jumble);

         guess(source, jumble);
         //printf("Random word is: %s\n ", words[randomNum]);
         //randomly jumble it           
}

void readFile(char *array[5049]) 
{
    char line[256]; //This is to to grab each string in the file and put it in a line. 
    int z = 0; //Indice for the array

    FILE *file;
    file = fopen("words.txt","r");

    //Check to make sure file can open 
    if(file == NULL)
    {
        printf("Error: File does not open.");
        exit(1);
    }
    //Otherwise, read file into array  
    else
    {
        while(!feof(file))//The file will loop until end of file
        {
           if((fgets(line,256,file))!= NULL)//If the line isn't empty
           {
             int len = strlen(line); 
             if (len > 0 && line[len - 1] == '\n') line[len - 1] = '\0';
             array[z] = malloc(strlen(line) + 1);
             strcpy(array[z],line);
             z++;
           }    
        }
    }
    fclose(file);
    numWords = z; 
}

void jumbleWord(char *word)
{
    int wordSize = strlen(word) - 1; 
    //durstenfeld Implementation of Fischer-Yates Shuffle
        int i; 
        int j; 
        char temp;
        for(i = wordSize - 1; i > 0; i--)
        {
            j =  rand() % (i + 1);
            temp = word[j];
            word[j] = word[i];
            word[i] = temp;
        }
}

void guess(char *word, char *jumbleWord)
{
     printf("original word is: %s\n", word);
     printf("jumbled word is: %s\n", jumbleWord);
     printf("source is: %s and jumbled word is: %s\n", word, jumbleWord);
}

我认为此时大多数人会烧掉C并为自己吸得如此糟糕而扇耳光。但是,我将继续运输。所以让我为任何愚蠢的行为道歉,但请知道我已经花了很多时间可能真的很愚蠢并盯着这个。我很想说,“嘿,C 太愚蠢了,因为它不会按照我说的去做”。不幸的是,我无法相信这一点。我认为它正在做我告诉它做的事情,但我离这个问题太近了,看不出我做错了什么。

一如既往,感谢您的帮助。我最深的敬意,GeekyOmega

4

2 回答 2

15

'\r'您在单词的末尾有一个回车符。

回车将写入光标移动到屏幕的左侧,因此它正在写入它,但它正在覆盖已经存在的内容。

于 2012-08-01T19:59:56.697 回答
2

你的words文件真的有5049条目吗?即使它没有,你也不应该假设它有。您的readFile函数应该在读取文件后确定数组中实际存在的单词数words,否则,将随机索引放入words数组将导致访问未初始化的字符串,我怀疑这会导致您的内存损坏。

所以,如果readFile只看到10 个单词,你应该只在 indices 之间选择一个随机单词0..9。您已经在方法中保留了变量z中的单词数readFile,并与您的其余代码共享。

当您为数组选择随机索引时,请注意,由于数组是从 0 开始的,因此您应该通过有效数组元素的数量获得随机数和 mod。所以使用int randomNum = rand() % 5049;没有+1.

此外,所有这些strlen/+1/-1东西都是不必要的和令人困惑的,更喜欢strncpy( memcpyand strcpy) 字符串,你不需要处理它。请注意, 的结果strlen 包括空终止符,因此您无需使用-1. 我认为您的jumbleWord功能应该始终忽略char混乱中的最后一个。

使用此策略分配字符串:您有MAX_WORD_LENGTH, 在游戏中将字符串声明为char word[MAX_WORD_LENGTH + 1]char *word = malloc(MAX_WORD_LENGTH + 1)。现在要复制字符串,请使用strncpy(src, dest, MAX_WORD_LENGTH).

于 2012-08-01T20:02:57.233 回答