首页 > 解决方案 > 随机词生成器中的奇怪输出

问题描述

我在以下程序的输出中遇到了一些问题。该程序随机生成单词,首先是随机辅音,然后是随机元音,然后再次生成您想要的最大字母数。

当我打印生成后立即生成的单词时,它会按预期给我一个单词列表。当我退出单词生成和堆叠循环并再次打印单词的输出时,我将所有单词混合成一个长链,这真的很奇怪。怎么了?

#include <stdio.h>

#define MAXWORDS 10
#define MAXLETTERS 6

int lcg(int Xcur)       /*linear congruential generator*/
{
    int A = 445, C = 700001, M = 2097152;
    int Xnext = (A * Xcur + C) % M;
    return Xnext;
}

int main()
{
    int x;
    printf("input seed for linear congruential generator: ");
    scanf("%d",&x);

    char consonants[]="bcdfghjklmnprstvwxz";
    char vowels[]="aeiou";

    int i,j;
    int turn;

    char words[MAXWORDS][MAXLETTERS];

    for(i=0;i<MAXWORDS;i++)
    {
        turn=1;

        for(j=0;j<MAXLETTERS;j++,turn++)
        {
            x=lcg(x);           /* random number generated */

            if(turn%2)          /* one consonant, one vowel, in turn */
                words[i][j]=consonants[x%19];
            else
                words[i][j]=vowels[x%5];
        }

        words[i][j]='\0';

        /* print each word generated */
        printf("word %d: %s\n", i+1, words[i]);
    }

    /* print the first word again */
    printf("\n\nthe 1st word again: %s\n",words[0]);

    return 0;
}

输出:

input seed for linear congruential generator: 23
word 1: wuduca
word 2: navozo
word 3: depiza
word 4: jukiti
word 5: raliwi
word 6: danila
word 7: cexewi
word 8: bamohu
word 9: jiruzi
word 10: temomo


the 1st word again: wuducanavozodepizajukitiraliwidanilacexewibamohujiruzitemomo

标签: carraysmultidimensional-arraystdio

解决方案


这是因为 is 以连续方式存储,没有任何空字符。

方法1:如果你只是想正确打印它,你可以通过写下面的行来做到:

printf("\n\nthe 1st word again: %s\n",words[0]);

作为

printf("\n\nthe 1st word again: %.*s\n",MAXLETTERS, words[0]);

方法二:

将单词声明为

char words[MAXWORDS][MAXLETTERS+1];

并将内部 for 循环写为

for(j=0;j<MAXLETTERS;j++,turn++)
{   
    x=lcg(x);           /* random number generated */

    if(turn%2)          /* one consonant, one vowel, in turn */
        words[i][j]=consonants[x%19];
    else
        words[i][j]=vowels[x%5];
}
words[i][MAXLETTERS] = '\0';

推荐阅读