2013-10-14 66 views
0
#include <iostream> 
#include <math.h> 
#include <string.h> 

using namespace std; 

int main() 
{ 
    cout << "My Funny Program"; 

    do { 
     string Answer; 
     cout << "Are you stupid? (Yes/No)"; 
     cin >> Answer; 
     cout << endl; 
     cout << "Perhaps you are lying?"; 
    } 
    while (Answer == "No"); 

    cout << "Thank you for your honesty." << endl; 

    return 0; 
} 

我一直在試圖讓此代碼正常工作;但是,每次出現錯誤「答案未在此範圍內聲明」時都會彈出。錯誤:未在此範圍內聲明「答案」

+2

請不要將隨機的東西放在'tags'字段中。 – SLaks

+3

這是一個範圍問題,看看你在哪裏宣佈'答案'和你在哪裏使用它... – MadProgrammer

+0

那麼我應該把答案? – user2877477

回答

1

我認爲while條件超出了範圍,如果塊本身。所以string Answer必須在循環之外定義。

風格推薦:帽子用於類或常量或宏。避免將它們用於變量。

0
do{ 

     string Answer; 
     cout<< "Are you stupid? (Yes/No)"; 
     cin>>Answer; 
     cout<< endl; 
     cout<< "Perhaps you are lying?"; 

    } 

    while (Answer == "No"); 

由於Answer是在do-while內聲明的,while部分不知道Answer的存在。

你必須之前做,而

0

Answer變量目前只有在它宣佈{}之間的範圍(循環體內)宣佈答案。您需要在循環之前聲明Answer

string Answer; 
do { 
    cout << "Are you stupid? (Yes/No)"; 
    cin >> Answer; 
    cout << endl; 
    cout << "Perhaps you are lying?"; 
} 
while (Answer == "No"); 
0

有趣的節目......

聲明的do-while循環將解決你的問題之外的答案。你

string Answer; 
do { 

     cout << "Are you stupid? (Yes/No)"; 
     cin >> Answer; 
     cout << endl; 
     cout << "Perhaps you are lying?"; 
    } 
    while (Answer == "No"); 

也應該使用的<string>代替<string.h>

0
do { 
     string Answer; 
     cout << "Are you stupid? (Yes/No)"; 
     cin >> Answer; 
     cout << endl; 
     cout << "Perhaps you are lying?"; 
    } 
    while (Answer == "No"); 

do你宣佈一個字符串變量Answer。然後,Answer被推入堆棧,但是,當程序計入}時,變量將被強制升高,這意味着在while語句中,Answer已被釋放,並且編譯器將Answer視爲未定義的變量。