2012-03-07 7 views
1
void offer_help(); 
bool play_one_game(); 

int main() { 

    offer_help(); 

    play_one_game(); 

} 


void offer_help() { 

    int help_response; 

    cout << "Need help? (0/1) "; 
    cin >> help_response; 
    if (help_response == 1) 
    cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n Each guess that you enter will be a line containing 4 integers,\n separated by spaces, such as:\n\t 2 4 7 1\n FOr each guess, I will echo back a lost consisting of\n 0's and 1's, with a 1 in a given position meaning that\n you guessed the number, and a zero meaning that you didn't.\n For example, if the actual solution was 2 3 6 1, I'll respond\n\t 1 0 0 1\n See how many guesses it takes you to get the solution!\n\n If you want to give up, type a negative number for one of\n your guesses, and we'll tell you what the pattern was.\n\n"; 

} 

bool play_one_game() { 

    srand(time(0)); //needed to start randint 

    vector<int> solution; //vector of 4 randomly generated 
       //solutions 
    vector<int> guess; //vector containing user guesses. 
    vector<int> result; 

    int guess_input; 

    for(int i = 0; i < solution.size(); ++i) 
    solution[i] = randint(10); 

    int trial_number = 0; //int that shows what guess the user is on 

    while (play_one_game() == true) {  
    //ask user for inputs. 
     cout << "Guess #" << ++trial_number << "? "; 
     for (int i = 0; i < guess.size(); ++i){ 
      cin >> guess_input; 
      guess.push_back(guess_input); 
     } 

     //outputs error if user inputs a letter. 
    if (!cin) { 
     cerr << "Bad input data! Feed me numbers!\n"; 
     return 43; 
    } 
    if (cin < 0){ 
     cout << "Too bad! Solution was " << endl; 
     for(int i = 0; i < result.size(); i++) 
     cout << (result[i]); 
    } 

    //determines if user correctly guessed any of the 
    //numbers and tells the user which is correct. 
    for (int i = 0; i < result.size(); i++) { 
     if (guess[i]==solution[i]) 
     cout << 1 << " "; 
     else if (guess[i]!=solution[i]) 
     cout << 0 << " "; 
    } 
    cout << endl; 

    // playagain(); 
    cout << endl << "Play again (0/1)? "; 
    int replay; 
    cin >> replay; 
    if (replay == 0) { 
     play_one_game() == false; 
     return 5; 
    } 
    else if (replay == 1) 
     play_one_game() == true; 
    else { 
     cerr << "wat?\n"; 
     return 10;  
    } 
    } 
} 

이것은 플레이어가 임의의 숫자 패턴을 추측 할 수 있도록 설계되었습니다.벡터 관련 분할 오류

나는 세그먼트 오류를 ​​얻고있다 왜 생각. 프로그램은 offer_help 함수를 호출 한 다음 main 함수 내에서 play_one_game 함수를 호출합니다. 그런 다음 다시 연주하고 싶은지 여부를 플레이어에게 확인해야합니다. 그렇지 않으면 bool play_one_game을 false로 설정하고 종료해야합니다.

이는 play_one_game의 불리언 기능에 관한 것이다.

+0

확인 경계 - 당신은()'[I]를 '하지만, 접근'[I]를 추측'와'솔루션 result.size'까지 반복하고 있습니다. –

답변

5

당신은, 세그먼트 오류가 있어요 :

while (play_one_game() == true) { 

play_one_game이 줄에 play_one_game를 호출하고, 이것은 다시 같은 줄에 play_one_game를 호출합니다 . 결국 스택 오버플로가 발생합니다.

더 나은 몇 가지 bool keepPlaying;while(keepPlaying) 대신 사용합니다.

편집 : 음, 이것은 간단한 대답보다 조금 더,하지만 난 게임을 좋아, 그래서 ... 다음 코드를 살펴 있습니다

#include <iostream> 
#include <ctime> 
#include <cstdlib> 
#include <vector> 

bool play_one_game(); 

void offer_help() { 
    int help_response; 
    std::cout << "Need help? (0/1) "; 
    std::cin >> help_response; 
    if (help_response == 1) 
     std::cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n" 
      "Each guess that you enter will be a line containing 4 integers,\n" 
      "separated by spaces, such as:\n" 
      "\t 2 4 7 1\n" 
      "For each guess, I will echo back a lost consisting of\n" 
      "0's and 1's, with a 1 in a given position meaning that\n" 
      "you guessed the number, and a zero meaning that you didn't.\n" 
      "For example, if the actual solution was 2 3 6 1, I'll respond\n" 
      "\t 1 0 0 1\n" 
      "See how many guesses it takes you to get the solution!\n\n" 
      "If you want to give up, type a negative number for one of\n" 
      "your guesses, and we'll tell you what the pattern was.\n\n"; 
} 

int main() { 
    offer_help(); 
    srand(time(0)); // Initialize random numbers with current time as seed 
    while(play_one_game()); // if play_one_game returns true, play again 
} 

bool play_one_game() { 
    std::vector<int> solution(4); // Four solutions for our guessing game 
    std::vector<int> guess;   // User guesses 

    for(unsigned i = 0; i < solution.size(); ++i) 
     solution[i] = rand() % 10; 

    int trial_number = 0; //int that shows what guess the user is on 
    bool keepPlaying = true; 
    while(keepPlaying){ 
     std::cout << "Guess #" << ++trial_number << "? "; 

     guess.clear(); // Clear old guesses 
     for(unsigned i = 0; i < solution.size(); ++i){ 
      int guess_input; 
      //outputs error if user inputs a letter. 
      if (!(std::cin >> guess_input)) { 
       std::cerr << "Bad input data! Feed me numbers!\n"; 
       std::cerr << "Try again!" << std::endl; 
       std::cin.clear(); // Clear flags 
       continue; 
      } 
      if (guess_input < 0){ 
       std::cout << "Too bad! Solution was " << std::endl; 
       for(unsigned i = 0; i < solution.size(); i++) 
        std::cout << (solution[i]); 
       keepPlaying = false; 
       break; 
      }else 
       guess.push_back(guess_input); 
     } 
     if(!keepPlaying) 
      break; 
     if(solution.size() != guess.size()){ 
      std::cerr << "Wrong number of guesses, try again!" << std::endl; 
      continue; 
     } 
     //determines if user correctly guessed any of the 
     //numbers and tells the user which is correct. 
     bool correct = true; 
     for (unsigned i = 0; i < solution.size(); i++) { 
      if (guess[i] == solution[i]) 
       std::cout << 1 << " "; 
      else{ 
       correct = false; 
       std::cout << 0 << " "; 
      } 
     } 
     if(correct){ 
      std::cout << "Congratulations - you won!" << std::endl; 
      break; 
     } 
     std::cout << std::endl; 
    } 
    int replay = -1; 
    do{ 
     // Ask user for input until input is 0 or 1 
     std::cout << std::endl << "Play again (0/1)? "; 
     std::cin >> replay; 
    } 
    while(replay != 0 && replay != 1); 
    return static_cast<bool>(replay); // return user replay answer (false/true) 
} 

Try to keep your code as simple as possible합니다. 에 오신 것을 환영합니다. 그리고 기대하지 않는 미래의 대답은 과도한한다.

+0

예! 스택 오버플로. 'play_one_game() == false'와 같은 호출도 있습니다. – Johnsyweb

3

당신은 결코 솔루션 벡터에 아무것도 삽입하지 있습니다. 당신은 벡터를 선언하고 말 :이 시점 solution.size() == 0에 있기 때문에 아무것도하지 않습니다

for(int i = 0; i < solution.size(); ++i) 
    solution[i] = randint(10); 

.... 나중에 결과 벡터를 반복 할 때 빈 솔루션 벡터의 잘못된 요소에 액세스하게됩니다. 결과 벡터와 솔루션 벡터가 같은 크기라고 가정 할 수도 없습니다. 당신이 다음 줄의 무한 재귀에서 생을 마감하기 때문에