猜字游戏赢了不能终止for循环

Can't terminate the for loop when winning a word guessing game

我已经编写了 猜字游戏的代码;

  1. 代码从单词文件中随机取一个单词,在文件中,每行有“1”个单词。

  2. 代码然后将这个单词转换成星号,在代码为运行的时候显示出来。

  3. 它会提示 运行 程序的任何人输入一个字母。如果字母正确,则该字母对应的星号将成为该字母。如果不是,程序会提示再次猜测。

尝试次数由用户在程序运行ning时设置。该程序称为 wordguess,因此在命令提示符下它是 运行 使用 "wordguess filename.txt n"

filename.txt指的是包含可供选择的单词的文件。 n指的是在输掉游戏之前允许用户尝试的次数。如果这个人在选定的尝试次数内没有猜到这个词,我可以让游戏结束,但如果这个人赢了,我似乎无法让游戏结束。如果单词猜对了,循环仍将继续,直到 运行 猜完为止。我不确定在循环中放置什么条件以促进获胜。我已经尝试了各种 if 语句,但是当我尝试时代码没有 运行。

    //taking random word from file
    srand(time(0));
    f = fopen(argv[1], "r");
    while (!feof(f))
    {
        fgets(word, 1024, f);
        word[strcspn(word, "\n")] = '[=10=]';
        nL++;
    }
    randomline = rand() % nL;
    fseek(f, 0, SEEK_SET);
    for (i = 0; !feof(f) && i <= randomline; i++)
        fgets(word, 1024, f);
        word[strcspn(word, "\n")] = '[=10=]';
    strcpy(astword, word); //copies word to another char
    for (i = 0; i < strlen(astword); i++)
    {
        astword[i] = '*'; //copy is converted to asterisks
    }
    int counter = 0;
    for (i = 0; i < tries; i++)
    {
        printf("%s \n", astword);
        printf("guess a letter\n");
        scanf(" %c", &guess);
        for (i = 0; i < tries; i++)
{
    printf("%s \n", astword);
    printf("guess a letter\n");
    scanf(" %c", &guess);

    for (j = 0; j < tries; j++)
    {
        if (guess == word[j])
            astword[j] = guess;
    }   
}

我是不是遗漏了什么明显的东西?

编辑: 根据 Ozan 的回答,我修改了我的循环,但它似乎不起作用;

        for (j = 0; j < tries; j++)
        {

            if (guess == word[j]) 
            {
                astword[j] = guess;
                counter++; 
            }

            if (counter == strlen(astword))
            {
                break;
            }
        }

如果我对你的问题理解正确,你只是想找到正确的逻辑来终止你的 for 循环。如果你想在用户猜对所有字母时终止循环,你可以通过计算你的程序做了多少 asterisk->letter 替换以及当计数达到你单词的字母数,那么是时候终止循环了,因为这意味着没有更多的星号可以猜测并且单词被猜对了所有缺失的字母..

在您程序的以下代码块中(发生替换的地方);

for (j = 0; j < tries; j++){
    if (guess == word[j])
      astword[j] = guess;
}   

只需添加一个计数器来计算星号(*)字母[替换了多少次] =35=];

for (j = 0; j < tries; j++){
  if (guess == word[j]){
    astword[j] = guess;
    counter++; // int variable, initialized to 0 before for loop starts
  }
}

并且在外部 for 循环 的开始处,添加一个 if 语句 来检查 counter 是否等于strlen(astword);

if (counter == strlen(astword))
      break; // if the replacement action is occured with the same number of word's lenght, break the loop.

所以作为上述代码的组合,你的for循环一定是这样处理break情况的;

for (i = 0; i < tries; i++){
    if (counter == strlen(astword))
      break;
    printf("%s \n", astword);
    printf("guess a letter\n");
    scanf(" %c", &guess);

    for (j = 0; j < tries; j++)
    {
        if (guess == word[j]){
            astword[j] = guess;
            counter++;
        }
    }   
}