2016-02-22 4 views
1

Я пробовал искать ответ и исправлять это сам, но я потерпел неудачу. Я пытаюсь создать программу, которая выполняет игру с угадыванием букв. Пожалуйста, имейте в виду, что это домашнее задание. Тем не менее, я не ищу ответов, я ищу прозрение. После выполнения этой программы я получаю сообщение об ошибке «Переменная„решение“используется без инициализации C++.Переменная используется без инициализации C++

Любые идеи?

#define _CRT_SECURE_NO_WARNINGS 
    #include <stdio.h> 
    #define MAXGUESSES 4 
    void GuessItRules(); 
    int PlayOneGame(char); 
    char GetTheLetter(); 
    int IsAWinner(char, char); 
    void CompareTheLetters(char guess, char letter); 



    int main() 
    { 
    //declare additional variables 
    //declare FILE pointer 
    FILE *inp; 
    int numGames, i = 0; 
    //letter from file 
    char letter; 
    //variable for the return of the PlayOneGame function 
    int didYouWin; 


    char solution; 


    //display instructions 
    GuessItRules(); 
    //connect to the file HINT: use fopen 
    inp = fopen("letterinput.txt", "r"); 

    //get number of games to play 
    printf("How many games? (1 to 5): "); 
    scanf("%d", &numGames); 

    //this for loop will allow the player to play more than one game 
    //without recompiling 
    for (i = 0; i < numGames; i++) 
    { 
     //get a letter from file - use fscanf 
     fscanf(inp, "%c", &letter); 
     //print the letter back onto the screen, just to test 
     //printf("\nThe letter is %c\n", letter); 

     //Play one game (Call PlayOneGame function) 
     //remember the function has an int return type 
     printf("Let's play game %d\n", i + 1); 
     PlayOneGame(solution); 
     //tell the player if they have won or lost (test the variable didYouWin) 

     } 

     //close file 
    fclose(inp); 
    return 0; 
} 




    char GetTheLetter() 
    { 
    char guess; 
    printf("\nMake a guess (CAPITAL LETTERS ONLY):"); 
    scanf("%c", &guess); 
    return guess; 
    } 

    void CompareTheLetters(char guess, char letter) 
    { 
    if (guess == letter) 
    { 
     printf("\nThe Letter and the guess are the same (%c)\n",guess); 
    } 
    else 
    if (guess < letter) 
    { 
     printf("The letter comes after your guess (%c)", guess); 
    } 
    else 
    if (guess > letter) 
    { 
     printf("The letter comes before your guess (%c)", guess); 
    } 

    } 

    int IsAWinner(char guess, char letter) 
    { 
    if (guess == letter) 
    { 
     return 1; 
    } 
    else 
     if (guess < letter) 
     { 
      return 0; 
     } 
     else 
      if (guess > letter) 
      { 
       return 0; 
      } 
    } 

    int PlayOneGame(char solution) 
    { 
    int numGuesses = 0; 
    //SHOULD BE INITIALZED TO 1 
    int winOrLose = 1; 
    // user guess 

    char guess = 0; 

    //char solution = 0; 
    char letter = 0; 


    //As long as the user has not used up the maximum number 
    //of guesses and has not guessed correctly 
    //the game will continue using this while loop 
    while (numGuesses < MAXGUESSES && winOrLose == 1) 
    { 
     printf("Getting guess number %d\n", numGuesses+1); 
     //function call to GetTheletter - returns to guess variable 
     GetTheLetter(); 
     //function call to IsAWinner - returns to winOrLose variable (0 or 1) 
     IsAWinner(guess, letter); 
     //function call to CompareTheLetters - gives the user a message 
     CompareTheLetters(guess, letter); 
     //update counter for number of guesses used 
     numGuesses = numGuesses + 1; 

    } 

    return winOrLose; //(0 or 1) 

    } 

    //add the other function definitions 

    void GuessItRules() 
    { 
    printf("Welcome to the Letter Guessing Game\n"); 
    printf("\nFirst, you will enter the number of games you want 
    to play (1 - 5  games)\n"); 
    printf("For each game you will have 4 chances to guess each letter\n"); 
    printf("Let's begin:\n"); 
    } 
+0

Прочитать предупреждение. Это довольно ясно. Что такое переменная 'solution'? – John3136

+0

Спасибо за быстрый ответ. Я добавил «char solution» для инициализации «PlayOneGame (Solution)». Я некоторое время отслеживаю сообщения об ошибках и добавляю, где говорится, что у меня есть ошибка. Это был единственный способ, которым я и мой основной опыт рассказывали мне тоже. Благодаря! – TheJr

+1

Возможный дубликат [Что происходит с объявленной, неинициализированной переменной в C? Имеет ли это значение?] (Http://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value) –

ответ

1

Вы получаете это предупреждение, потому что вы объявляете char solution, а затем передать он по значению для функции PlayOneGame(char solution), не инициализируя ее. Поскольку вы передаете ее таким образом, вы подразумеваете, что собираетесь использовать ее как константу (а не const ... Я имею в виду, что вы передаете только значение, это не ссылка на него, поэтому в функции она не изменена ...). В ее основе вы вообще не используете ее, но это относится к сообщению.

+0

Thank вы за нарушение и помогли мне решить эту проблему. Однако я понял, что мне пришлось инициализировать решение с помощью char решения для определения решения в PlayOneGame (решение). – TheJr

+0

@TheJr ваша функция использует pass-by-value, что означает, что функция получает копию аргумента. Чтобы делать то, что вы описываете, необходимо использовать * pass by reference *. –

+0

Как бы я это сделал, точно? &Значение? – TheJr