2017-05-10 33 views
1

允許我在前面說,我確實包含了(也適用於string,endl,並且確實無所不在)。就語法而言,我的IDE沒有顯示任何錯誤;我不明白爲什麼會發生這個問題?它在我編寫的其他C++代碼示例中運行良好。Cout不是std的成員,還有其他關於C++的問題

所以我試圖做一個小遊戲,公牛和牛。我的主要代碼如下:

#include <iostream> 

#include "stdafx.h" 
#include "BullsAndCows.h" 



using std::cout; 
using std::endl; 
using std::cin; 
using std::string; 

int main() 
{ 

    string userInput = ""; 
    bool playAgain = false; 

    int gameDiff; 

    constexpr char * GREETING = "Welcome to Bulls and Cows! Please enter the difficulty level: (1) Easy, (2) Medium, (3) Hard"; 

    cin >> gameDiff; 

    do 
    { 
     BullsAndCows *bc = new BullsAndCows(); 
     bc->playGame(gameDiff); 

    } while (playAgain); 


    constexpr char * INFORMATION = "Total Word Length is: "; 

    //Introduce the game. 

    cout << GREETING <<endl; 

    return 0; 
} 

我的頭:

#ifndef BULLSANDCOWS_H 
#define BULLSANDCOWS_H 



class BullsAndCows { 

public: 


    void playGame(int gameDiff); 


}; 

#endif 

最後,我BullsAndCows.cpp文件:

#include <iostream> 
#include <string> 
#include "stdafx.h" 
#include "BullsAndCows.h" 

using std::cout; 
using std::endl; 
using std::cin; 
using std::string; 

void BullsAndCows::playGame(int gameDiff) { 

    string wordGuess = ""; 
    string secretWord = ""; 
    int numBulls = 0; 
    int numCows = 0; 
    int numGuesses = 0; 

    switch (gameDiff) 
    { 

    case 1: { 
     numGuesses = 30; 

     secretWord = "Hello"; 

     for (int i = 0; i < 30; i++) { 

      numBulls = 0; 
      numCows = 0; 

      cout << "Word Length to Guess Is Five, you have " << numGuesses << " guesses remaining" << endl; 
      cout << "Enter your word guess"; 
      cin >> wordGuess; 

      for (int j = 0; j < wordGuess.length; j++) { 
       if (wordGuess.at(j) == secretWord.at(j)) { 
        numBulls++; 
       } 
       else if (secretWord.find(wordGuess.at(j)) != -1) { 
        numCows++; 
       } 
      } 

      cout << "Bulls: " << numBulls << endl; 
      cout << "Cows: " << numCows << endl; 

      if (numBulls == secretWord.length) { 
       cout << "YOU WIN!" << endl; 
       break; 
      } 

     } 

     break; 
    } 
     case 2: 
      numGuesses = 20; 
      break; 
     case 3: 
      numGuesses = 10; 
      break; 
    } 

} 

錯誤我正在爲「COUT是不是成員的標準「,cout符號不能用在使用聲明中。在此之前,我使用「使用命名空間標準」,並會返回錯誤,如「公牛隊」並不是一個命名空間或類(如果它不是一個類,那麼我必須是一個火星人)。還有一些關於失蹤的「;」在userInput之前,例如在我的main.cpp代碼中;這是沒有意義的,因爲沒有什麼東西是缺少的。我正在使用VS2017。爲什麼C++這樣惱人的語言可以工作?

+0

其中一個與{在案例1的開始相關。我不知道爲什麼它會拋出所有這些錯誤。它確實使0感覺。 – SomeStudent

+0

你真的需要一個[mcve],但是從這裏發佈的代碼中,main.cpp不能看到'std :: string'的定義,所以添加一個'#include '到main.cpp – AndyG

+0

這是一個特性的Visual Studio而不是C++本身?由於我已經對它做了任何事情,所以年齡已經過去了,但是'#include「stdafx.h」'之前的任何內容都會因爲自動預編譯而被忽略。 '#include「stdafx.h」'後面的'#include '會發生什麼? –

回答

4

將指令

#include "stdafx.h" 

之前的任何其他包括指令。

+0

Spasibya。 100%。我的頭剛剛在我的桌子上做了一箇中國大小的洞。當我製作更多文件/項目時,我會在未來記住這一點。一旦定時器允許我接受你的答案。 – SomeStudent

+0

@SomeStudent根本沒有。不用謝。 –

+0

我建議不要使用預編譯頭文件。您應該測量它爲您節省了多少編譯時間,並確定預編譯頭文件是否值得。 –