2012-02-23 2 views
1

내 코드에 문제가 있습니다. 게임을 만들려고하는데 주 루프에 도달 할 때 오류가 발생합니다. 나는 코드와 내가받는 오류를 보여줄 것이다.while 및 switch 루프 관련 문제

옵션 1을 선택하고 게임을 재생할 때 정확한 답이 주어진 후 게임이 반복되고 플레이어에게 두 번째 임의의 단어가 표시되고 플레이어가 ' 떠나다'.

코드입니다 :

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

int main() 
{ 
    enum fields {WORD, HINT, NUM_FIELDS}; 
    const int NUM_WORDS = 3; 
    const string WORDS[NUM_WORDS][NUM_FIELDS] = 
    { 
     {"jumble1", "First word."}, 
     {"jumble2", "Second word."}, 
     {"jumble3", "Third word."} 
    }; 

    srand(static_cast<unsigned int>(time(0))); 
    int choice = (rand() % NUM_WORDS); 
    string theWord = WORDS[choice][WORD]; 
    string theHint = WORDS[choice][HINT]; 

    string jumble = theWord; 
    int length = jumble.size(); 
    for (int i = 0; i < length; ++i) 
    { 
     int index1 = (rand() % length); 
     int index2 = (rand() % length); 
     char temp = jumble[index1]; 
     jumble[index1] = jumble[index2]; 
     jumble[index2] = temp; 
    } 

    int choice; 
    bool choiceNotMade = true; 

    while (choiceNotMade) 
    { 
     cout << "[1] Play\n"; 
     cout << "[2] Credits\n"; 
     cout << "[3] Quit\n\n"; 

       cout << "Your choice: "; 
     cin >> choice; 
     } 

      switch (choice) 
      { 
      case 1: 
       cout << "Unscramble the letters to make a word.\n"; 
       cout << "Enter 'hint' for a hint.\n"; 
       cout << "Enter 'quit' to quit the game.\n\n"; 
       cout << "The jumble is: " << jumble; 

       string guess; 
       cout << "\n\nYour guess: "; 
       cin >> guess; 

       while ((guess != theWord) && (guess != "quit")) 
       { 
        if (guess == "hint") 
        { 
         cout << theHint; 
        } 
        else 
        { 
         cout << "That's not the right word."; 
        } 

        cout << "\n\nYour guess: "; 
        cin >> guess; 
       } 

       if (guess == theWord) 
       { 
        cout << "\nYou guessed it!\n"; 
       } 

       cout << "\nThank you for playing.\n"; 

       system("Pause"); 
       choiceNotMade = false; 
       break; 

      case 2: 
       cout << "\n\nThis game has been made by:\n\n"; 
       choiceNotMade = false; 
       break; 

      case 3: 
       cout << "Program will exit"; 
       exit(1); 

      default: 
       cout << "\nYou did not pick a valid option.\n\n"; 
       choiceNotMade = false; 
       break; 

       } 

    return 0; 
} 

그리고 이것은 오류입니다 :

word_jumble.cpp: In function `int main()': 
word_jumble.cpp:32: error: redeclaration of `int choice' 
word_jumble.cpp:17: error: `int choice' previously declared here 
word_jumble.cpp:83: error: jump to case label 
word_jumble.cpp:53: error: crosses initialization of `std::string guess' 
word_jumble.cpp:88: error: jump to case label 
word_jumble.cpp:53: error: crosses initialization of `std::string guess' 
word_jumble.cpp:92: error: jump to case label 
word_jumble.cpp:53: error: crosses initialization of `std::string guess' 
word_jumble.cpp:83: warning: destructor needed for `guess' 
word_jumble.cpp:83: warning: where case label appears here 
word_jumble.cpp:83: warning: (enclose actions of previous case statements requiring destructors in their own scope.) 
word_jumble.cpp:88: warning: destructor needed for `guess' 
word_jumble.cpp:88: warning: where case label appears here 
word_jumble.cpp:92: warning: destructor needed for `guess' 
word_jumble.cpp:92: warning: where case label appears here 
word_jumble.cpp:100:2: warning: no newline at end of file 
make[2]: *** [build/Debug/MinGW-Windows/word_jumble.o] Error 1 
make[1]: *** [.build-conf] Error 2 
make: *** [.build-impl] Error 2 

답변

1

나는 메시지

redeclaration of `int choice'

꽤 명백해야한다 생각합니다.

다른 오류 메시지는 이해하기가 조금 더 어렵지만 guessswitch 문 외부에 선언하면 사라집니다.

+0

하지만 실제로 이것이 무엇입니까? – DutchLearner

+1

@ user1222107 기술적 인 세부 사항을 모르지만이 경우 레이블은 새 블록을 만들지 않습니다. 해결책은 모든 변수를'switch' 문 밖에서 선언하거나'{}'블록에 넣는 것입니다. 'case X : {/ * stuff * /}'와 같은 것을 할 수 있고 내부에 선언 된 변수를 가질 수 있습니다. –

+0

좋아, 고마워. :) – DutchLearner

2

당신은 두 번 int choice를 선언하고 있습니다. 오류 메시지는 매우 명확합니다. 당신은 변수를 선언하면

, 당신은 동일한 범위에서 다시 선언 할 수 없습니다 :

{ 
    int x; 

    //... 
    int x; // <-- illegal, just use x 
} 
1

두 장소에서 choice을 선언했다. 또한 while 루프 외부에 switch을 작성 했으므로 프로그램을 컴파일하더라도 무한 루프에 걸릴 수 있습니다.

+0

@JoachimPileborg 당신이 choiceNotMade'가에서 FALSE ''로 설정하기'보입니까 'while'? –

+0

'switch'의 대안 3은 'exit'을 호출하고,'choiceNotMade'는 대안 2에서'false'로 설정되기 때문에 문제가되지 않습니다. –

+0

@JoachimPileborg 나는 'while (choiceNotMade)'루프는 무한 루프로 이어질 것입니다. 들여 쓰기를 살펴보면 루프 내에서 스위치를 쓰는 것처럼 보입니다. –

1

나는 이것이 숙제라고 생각하는데, 너무 구체적인 권장 사항에서 벗어날 것입니다.

당신은 라인 (19)에 변수 choice을 선언, 그래서 당신은 라인 (34) 당신은 또한 switch 문 앞에에 string guess의 선언을 이동해야

에서 두 번째 선언을 제거해야합니다. 이것은 C++이 모든 지역 컴파일러를 정확히 한 번 초기화해야하기 때문에 컴파일러가 루프를 처음으로 수행 할 때 case 2:을 가져오고 두 번째 시간이 case 1: 인 경우 string guess이 선언 된 경우이를 확인할 수있는 방법이 없기 때문입니다.

이렇게하면 프로그램을 컴파일 할 수는 있지만 예상대로 작동하지 않습니다. 프로그램의 여는/닫는 중괄호를보고 코드 블록이 예상대로 중첩되어 있는지 확인하십시오.

1

당신이 바로 전에, 다음 1 회, 2 회

int choice = (rand() % NUM_WORDS); 

int choice; 

을 선언하고있다

while (choiceNotMade)