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;
}

我一直试图让这段代码工作;但是,每次弹出错误“未在此范围内声明答案”时。

4

5 回答 5

1

如果块本身,我相信while条件超出了范围。所以string Answer必须在循环之外定义。

风格推荐:大写用于类或常量或宏。避免将它们用于变量。

于 2013-10-14T02:49:47.803 回答
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被压入堆栈,然而,当过程 encount 时},变量将被弹出,这意味着,在while语句中,Answer已被释放,编译器将其视为Answer未定义变量。

于 2013-10-14T03:13:39.247 回答
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>

于 2013-10-14T02:51:54.490 回答
0
 do{

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

    }

    while (Answer == "No");

由于在 do-while 中声明了 Answer,因此 while 部分不知道 Answer 的存在。

您必须在 do-while 之前声明 Answer

于 2013-10-14T02:50:20.833 回答
0

您的Answer变量目前仅在{}声明它的位置之间(在循环体内)。您需要Answer在循环之前声明。

string Answer;
do {
    cout << "Are you stupid? (Yes/No)";
    cin >> Answer;
    cout << endl;
    cout << "Perhaps you are lying?";
}
while (Answer == "No");
于 2013-10-14T02:51:28.440 回答