Home > Net >  CPP won't generate text?
CPP won't generate text?

Time:10-15

I have some CPP code to generate Lorem Ipsum style text. It works when I ask it for one sentence at a time, but when I tell it to mass generate sentences it generates tons of sentences that are just spaces and then periods. Here's the code (modified for confidentiality):

    srand(time(NULL));
    string a[9327] = {"Str1", "Str2", "Str3" . . .};
    int loop_1 = 0;
    int loop_2 = 0;
    while (loop_2 <= 100000) {
    while (loop_1 <= (rand() % 38)   2) {
        int value = rand() % (9327 - (rand() % (9327 - (rand() % (9327 - (rand() % 9327))))));
        cout << a[value] << " ";
        loop_1 = loop_1   1;}
    cout << "\b. ";
    loop_2 = loop_2   1;
    }

I'm sorry if this is an incompetent question. I'm a conlanger/composer normally but I had to throw together some code for a project––so I'm still just barely learning C .

CodePudding user response:

"Can you explain what does that weird formula that involves not just one, but four calls to rand() is supposed to accomplish? What does that mean to you? So, the first call to rand() produces 9326. The remainder when dividded by 9327 is 9326. Subtracting from 9327 produces 1. The next call to rand(), no matter what it is, the remainder of that value divided by 1 is 0. Hillarity ensues after the attempt to take 3rd call to rand(), and calculate the remainder when it gets divided by 0. Oops." -Sam Varshavchik (He answered in the comments, so I ported it here)

CodePudding user response:

Okay, I mean, this code doesn't make a lot of sense but to answer the question, note that the only way the inner loop can not issue random strings is if it never runs and it will not run if loop_1 is greater than (rand() % 38) 2 which is a random number from 2 to 40. Once loop_1 is greater than 40 the inner loop can never run, because loop_1 only increases. But anyway, before that occurs, if you want the inner loop to definitely run then test that it does, also might as well get rid of loop_2 because it isn't doing anything once loop_1 is greate than 40.

Replacing 9327 for 7, I get

int main() {
    srand(time(NULL));
    string a[7] = { "aaaaaaaaaa ", "bbbbbbbb ", "ccccccccccccc ", "dddddddd ", "eeeeeeeeeee ", "ffffffffff ", "ggggggg "};
    int loop_1 = 0;
    while (loop_1 < 40) {
        auto num = (rand() % 38)   2;
        if (loop_1 > num) {
            continue;
        }
        while (loop_1 <= num) {
            int value = rand() % (7 - (rand() % (7 - (rand() % (7 - (rand() % 7))))));
            cout << a[value] << " ";
            loop_1 = loop_1   1;
        }
        cout << "\b. ";
    }
}
  •  Tags:  
  • c
  • Related