我想知道我是如何在这个简单的 C 骰子游戏中加入循环的

I would like to know how i am meant to put a loop in this simple dice game in C

我想知道循环此代码的最佳方法。基本上它是一个骰子游戏,随机抽取 1 到 6 之间的数字。一旦数字显示给玩家,我想给他们一个选项“你想再玩一次吗?”如果他们输入 y 或 yes 则游戏重新开始。我猜我应该使用 while 循环,但我不确定该怎么做。任何帮助将不胜感激

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main() {
   int lower = 1, upper = 6, count = 1;
   srand(time(0)); 
   generate_random(lower, upper, count);
 }
void generate_random(int l, int r, int count) { 
   int i;
   for (i = 0; i < count; i++) {
      int rand_num = (rand() % (r - l + 1)) + l;
      printf("You rolled a %d", rand_num);
   }
}

很明显你想提示并允许用户“roll-again”。在您的代码中,滚动的是什么?这就是你想要循环的。在 main() 中似乎是:

    generate_random(lower, upper, count);

现在,当您应用 while 循环或 do ... while(); 循环时,必须注意如何接受输入。您可以简单地 getchar(),但您需要考虑用户按 Enter 生成的 '\n',否则当 getchar() 愉快地将 '\n' 作为您的下一个输入。 (如果用户输入 "Yes again!" 会怎样?)

所有新的 C 程序员都应该 user-input 使用 fgets() 和一个足以容纳行的预期内容的缓冲区(至少 32 个字符,或 2X 最大预期输入作为粗略 rule-of-thumb).这样即使用户输入 "Yes again!",所有字符都会被读入缓冲区并被使用——包括 '\n'.

您可以通过简单地取消引用缓冲区来轻松地检查用作缓冲区的 character-array 的第一个字符,例如

char buf[64] = "";

然后要检查缓冲区中的第一个字符,您可以使用:

*buf == 'n'

这是如何运作的?

*buf == *(buf + 0) == buf[0]

所以你只是检查数组第一个索引处的字符。

总而言之,你可以这样做:

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

#define MAXC 64     /* if you need a constant, #define one (or more) */

void generate_random(int l, int r, int count)
{
    for (int i = 0; i < count; i++)
        printf("You rolled a %d\n", rand() % (r - l + 1) + l);
}

int main (void) {
    
    int lower = 1, upper = 6, count = 1;
    char buf[MAXC] = "";                        /* array of 64 chars to use as a buffer */
                                                /* to hold the user-input */        
    srand(time(0));
    
    while (*buf != 'n' && *buf != 'N') {        /* loop while 1st char not 'n' or 'N' */
        generate_random(lower, upper, count);
        
        fputs ("\nwould you like to roll again (y/n)? ", stdout);   /* prompt again */
        if (!fgets(buf, sizeof buf, stdin))     /* read user-input & validate read */
            break;                              /* if user generates EOF break */
    }
}

A do .. while(); 循环将消除使用 buf[MAXC] = "";buf 初始化为 empty-string 的需要(显式初始化第一个字符 0 然后其余 63 个字符默认为 0)

例子Use/Output

$ ./bin/diceagain
You rolled a 3

would you like to roll again (y/n)? y
You rolled a 2

would you like to roll again (y/n)? Yes please again!
You rolled a 4

would you like to roll again (y/n)? Sure one more time...
You rolled a 4

would you like to roll again (y/n)? n

只要用户输入的字符数不超过 63 个,您就不会遇到在 stdin.

上留下未读无关字符的问题

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