C - 如何在游戏板(二维数组)中打印随机单词?

C - How can I print random word inside game board (2d array)?

我正在使用 C 语言和 Cygwin 终端编写打字游戏。

我从 .txt 文件中读取了 1000 个单词,然后打印了一个随机单词。我需要在二维数组框中打印这个随机词 "gameboard"

Link to: Image of current output. Need to move word from outside of box to inside of box.

如何在方框内打印我的随机单词?

单词需要出现在方框顶行的随机水平位置。

注意:当我说盒子时,我指的是一个由破折号和星号组成的 20(高)乘 80(宽)的盒子。

如有任何帮助,我们将不胜感激。非常感谢您。

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

void main(){

    int g, h; //index for use in for loop

        //creates box
    const int boxLength = 20;
    const int boxWidth = 75;
    char box[boxLength][boxWidth];
    for(int g = 0; g < boxLength; g++){
        for(int h = 0; h < boxWidth; h++){
            if(g == 0 || g == boxLength - 1)
                box[g][h] = '-';
            else if(h == 0 || h == boxWidth - 1)
                box[g][h] = '|';
            else
                box[g][h] = ' ';
            }
    }       

            FILE *myFilePointer2 = fopen("wordList.txt", "r");

            srand(time(0));
            int size = 1000;

            if(myFilePointer2 == NULL){
                printf("Unable to open file wordList.txt");
                exit(0);
            }

            char** words = (char**)malloc(sizeof(char**)*size); //2d pointer array, dynamically allocated, to store words from text file

            char wordBankArray[1050];//wordBankArray

            int wordQuantity = 0;

            while(fgets(wordBankArray, 1050, myFilePointer2) != NULL){// read data from myFilePointer line by line and store it into words array
                words[wordQuantity] = (char*)malloc(sizeof(char)*(strlen(wordBankArray)+1)); //dynamically allocates memory for words array
                strcpy(words[wordQuantity], wordBankArray); //copying words from text file to wordBankArray
                wordQuantity++;
            }

            printf("Randomly generated word from .txt file: ");
            int index = rand()%wordQuantity;   // psuedo randomly generates an index in range of 0 to wordQuantity)

            printf("%s\n", words[index]); //prints randomly generated word from index

            for(int g = 0; g < boxLength; g++){ //prints 2d box
                for(int h = 0; h < boxWidth; h++){
                    printf("%c", box[g][h]);
                }
                printf("\n");
                fclose(myFilePointer2); //close file for reading
            }
    }

你有一些小错误,如果你正在读取一个有 1000 个字的文件但只分配 100 个指针——你会调用未定义的行为试图写入不存在的指针。

您的 for(int g = 0; g < boxLength; g++){ 循环中不需要 fclose()(关闭文件 boxlength 次)。

如果您正在定义 const int ... 那么您将创建一个 2D VLA(可变长度数组),这很好,但是如果在编译时之前已知边界,请改为使用 #define 声明常量并避免 C89/90 中不存在的 VLA,在 C99 中引入并成为 C11 中的可选功能。

您还应该将 -Wshadow 添加到您的编译字符串中,您隐藏了变量:

int g, h; //index for use in for loop

声明循环变量时:

for(int g = 0; g < boxLength; g++){
    for(int h = 0; h < boxWidth; h++){
    ...

(小心你的变量声明——在这里你以后不要使用 gh,但在其他情况下,隐藏变量会产生可怕的后果)

考虑到这一点,您可以将所需的常量定义为:

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

#define BXLEN   20      /* if you need a constant, #define one (or more) */
#define BXWDT   75
#define WRDSZ  100
#define ARRSZ 1050

(名字随便取)

除非您在 独立环境(没有操作系统)中工作,否则您的 void main() 声明是错误的。在符合标准的实现中,main 的允许声明是 int main (void)int main (int argc, char *argv[])(您将看到用等效的 char **argv 编写)。参见:C11 Standard - §5.1.2.2.1 Program startup(p1).

参数 int argc, and char **argv 允许您在命令行上将信息传递到您的程序中。不要硬编码文件名。 (如果您使用的是嵌入式系统——那是一个例外,因为您可能无法在命令行上传递文件名)否则,您可以这样做:

int main (int argc, char **argv)
{
    int nptrs = WRDSZ, index, wordQuantity = 0;     /* declare/initialize vars */
    char box[BXLEN][BXWDT] =  {{0}},
        **words = NULL,
        wordBankArray[ARRSZ] = "";
    FILE *fp = NULL;

    if (argc < 2 ) {    /* validate 1 argument given for filename */
        fprintf (stderr, "error: insufficient input,\n"
                         "usage: %s filename\n", argv[0]);
        return 1;
    }

    /* open file/validate file open for reading */
    if ((fp = fopen (argv[1], "r")) == NULL) {
        perror ("fopen-argv[1]");
        return 1;
    }

(注意:我把myFilePointer2缩短为fp)

当你在C中使用malloccallocrealloc动态分配内存时,不需要转换malloc的return,这是不必要的。参见:Do I cast the result of malloc?。如果您使用解除引用的指针来设置您的类型大小——您将永远不会弄错。您可以为 words 分配指针:

    if (!(words = malloc (nptrs * sizeof *words))) {    /* allocate/validate */
        perror ("malloc-words");
        return 1;
    }

(注意:您必须验证每个分配)

注意上面,你只分配了一个初始的 WRDSZ (100) 指针。如果你的文件有 1000 个字,你必须跟踪填充的指针数(你的 wordQuantity)并且你必须跟踪分配的指针数(比如 nptrs)。当 wordQuantity == nptrs 时,您必须 realloc 通过 words 可用的指针数量,然后才能尝试使用另一个指针(通常将当前分配的数量加倍是一个合理的增长方案)。添加额外的测试和重新分配,您的读取循环将变为:

    while (fgets (wordBankArray, ARRSZ, fp) != NULL) {  /* read each line in file */
        size_t len;     /* save length, then memcpy */
        if (wordQuantity == nptrs) {    /* check if all pointers used - realloc */
            /* always realloc using a temporary pointer -- not the pointer itself */
            void *tmp = realloc (words, 2 * nptrs * sizeof *words);
            if (!tmp) {     /* validate realloc succeeds */
                perror ("realloc-words");
                break;      /* don't exit, original words pointer still valid */
            }
            words = tmp;    /* assign reallocated block to original pointer */
            nptrs *= 2;     /* update number of pointers allocated */
        }
        if (!(words[wordQuantity] = malloc ((len = strlen (wordBankArray)) + 1))) {
            perror ("malloc-words[wordQuantity]");
            return 1;
        }
        memcpy (words[wordQuantity], wordBankArray, len + 1);
        wordQuantity++;
    }
    fclose (fp);

(注意:你只需要调用一次strlen(),保存大小,然后用memcpy()复制字符串。如果你调用strcpy(),您只是再次扫描您在调用 strlen())

时已经拥有的字符串结尾

阅读完毕后,请在此时致电 fclose()。另请注意 sizeof (char)1 并且应该从您的大小乘法中省略。你所拥有的其余部分将打印框并输出一个随机字符串,但请注意输出中不需要转换的地方,不需要调用 printfputsfputs 都可以(好的编译器会在幕后为您进行更改)

你想念的是释放你分配的内存。为此你可以这样做:

    for (int i = 0; i < wordQuantity; i++)      /* free allocated strings */
        free (words[i]);
    free (words);                               /* free pointers */

如果你把这些放在一起,你可以这样做:

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

#define BXLEN   20      /* if you need a constant, #define one (or more) */
#define BXWDT   75
#define WRDSZ  100
#define ARRSZ 1050

int main (int argc, char **argv)
{
    int nptrs = WRDSZ, index, wordQuantity = 0;     /* declare/initialize vars */
    char box[BXLEN][BXWDT] =  {{0}},
        **words = NULL,
        wordBankArray[ARRSZ] = "";
    FILE *fp = NULL;

    if (argc < 2 ) {    /* validate 1 argument given for filename */
        fprintf (stderr, "error: insufficient input,\n"
                         "usage: %s filename\n", argv[0]);
        return 1;
    }

    for (int g = 0; g < BXLEN; g++) {                   /* initialize box */
        for (int h = 0; h < BXWDT; h++) {
            if (g == 0 || g == BXLEN - 1)
                box[g][h] = '-';
            else if (h == 0 || h == BXWDT - 1)
                box[g][h] = '|';
            else
                box[g][h] = ' ';
        }
    }

    /* open file/validate file open for reading */
    if ((fp = fopen (argv[1], "r")) == NULL) {
        perror ("fopen-argv[1]");
        return 1;
    }

    srand (time (NULL));                                /* seed rand generator */

    if (!(words = malloc (nptrs * sizeof *words))) {    /* allocate/validate */
        perror ("malloc-words");
        return 1;
    }

    while (fgets (wordBankArray, ARRSZ, fp) != NULL) {  /* read each line in file */
        size_t len;     /* save length, then memcpy */
        if (wordQuantity == nptrs) {    /* check if all pointers used - realloc */
            /* always realloc using a temporary pointer -- not the pointer itself */
            void *tmp = realloc (words, 2 * nptrs * sizeof *words);
            if (!tmp) {     /* validate realloc succeeds */
                perror ("realloc-words");
                break;      /* don't exit, original words pointer still valid */
            }
            words = tmp;    /* assign reallocated block to original pointer */
            nptrs *= 2;     /* update number of pointers allocated */
        }
        if (!(words[wordQuantity] = malloc ((len = strlen (wordBankArray)) + 1))) {
            perror ("malloc-words[wordQuantity]");
            return 1;
        }
        memcpy (words[wordQuantity], wordBankArray, len + 1);
        wordQuantity++;
    }
    fclose (fp);

    fputs ("Randomly generated string from list : ", stdout);
    index = rand() % wordQuantity;
    printf ("%s\n", words[index]);

    for (int g = 0; g < BXLEN; g++) {
        for (int h = 0; h < BXWDT; h++) {
            printf ("%c", box[g][h]);
        }
        putchar ('\n');
    }

    for (int i = 0; i < wordQuantity; i++)      /* free allocated strings */
        free (words[i]);
    free (words);                               /* free pointers */
}

示例Use/Output

对于数据文件dat/1kfnames.txt,我只是将1000个文件名重定向到文件中作为words:

$ ./bin/wordinbox dat/1kfnames.txt
Randomly generated string from list : str_printf_null.c

---------------------------------------------------------------------------
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
---------------------------------------------------------------------------

内存Use/Error检查

在您编写的任何动态分配内存的代码中,您对分配的任何内存块负有 2 责任:(1) 始终保留指向内存块的起始地址 因此,(2) 当不再需要它时可以释放

您必须使用内存错误检查程序来确保您不会尝试访问内存或写入 beyond/outside 您分配的块的边界,尝试读取或基于未初始化的条件跳转值,最后,确认您释放了所有已分配的内存。

对于Linux valgrind是正常的选择。每个平台都有类似的内存检查器。它们都很简单易用,只需运行你的程序就可以了。

$ valgrind ./bin/wordinbox dat/1kfnames.txt
==28127== Memcheck, a memory error detector
==28127== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==28127== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==28127== Command: ./bin/wordinbox dat/1kfnames.txt
==28127==
Randomly generated string from list : tor.c

---------------------------------------------------------------------------
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
---------------------------------------------------------------------------
==28127==
==28127== HEAP SUMMARY:
==28127==     in use at exit: 0 bytes in 0 blocks
==28127==   total heap usage: 1,008 allocs, 1,008 frees, 45,566 bytes allocated
==28127==
==28127== All heap blocks were freed -- no leaks are possible
==28127==
==28127== For counts of detected and suppressed errors, rerun with: -v
==28127== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

始终确认您已释放所有分配的内存并且没有内存错误。

检查一下,如果您还有其他问题,请告诉我。

您可以尝试这样的操作:

获取单词数组和 select 一个随机单词,就像您已经在代码中所做的那样。在这里,我假设随机词是 'randomWord'.
然后使用rand()函数获取随机词位置,如下代码所示。

char randomWord[20]="Program";
int wordLen = strlen(randomWord);
srand(time(0));
//Generates the random position of the word
//Subtract '2' because of the borders of the box and the word length so it can fit in the box
int wordPos = rand() % (boxWidth-wordLen-2);

for(int g = 0; g < boxLength; g++){
    for(int h = 0; h < boxWidth; h++){
        if(g == 1 && h == wordPos){ //Inserts the word at the top and at the random position
            for(int i = 0; i < wordLen; i++){
                box[g][h] = randomWord[i];
                h++;
            }
            box[g][h] = ' ';
        }
        if(g == 0 || g == boxLength - 1)
            box[g][h] = '-';
        else if(h == 0 || h == boxWidth - 1)
            box[g][h] = '|';
        else
            box[g][h] = ' ';
    }
}

然后像您已经在做的那样简单地打印盒子。
你应该看到这样的东西:
Result of the box with the random word inside

希望对您有所帮助!