成员函数不会执行它的全部代码

Member function will not execute its whole code

我做了一个"computer"。我的构造函数如下所示:

PC::PC()
{
    cout << "Would you like to turn the pc on? type y for yes." << endl;
    a = getchar();

    while (a != 'y')
    {
        cout << "If you dont turn it on, then nothing will happen. Loser." << endl;
        a = getchar();
    }
}

然后,如果您按 y,您将被转到下一步,即函数 PC::pcOn,如下所示:

void PC::pcOn()
{
    for (auto i = 0; i < 3; i++)
    {
        cout << "----------------------------------------" << endl;
    }
    cout << "--------- What is your name? -----------" << endl;
    changeName();
    for (auto i = 0; i < 3; i++)
    {
        cout << "----------------------------------------" << endl;
    }

    for (auto i = 0; i < 5; i++)
    {
        cout << "**" << endl;
        Sleep(100);
    }
    cout << "Welcome " << name << " to the future of computing." << endl << endl;
    cout << "This computer program can do a lot of things for you" << endl << "it is a good calculator, try to type \"calculater\"" << endl;
}

然而,当我在构造函数中使用 while 循环来让 y 继续时,changeName();不会工作,但如果我删除它,changeName 函数就可以正常工作,并且它可以很好地接受我的输入。

changeName() 的代码如下所示:

void PC::changeName()
{
    string _name;
    getline(cin, _name);
    name = _name;
}

我已经尝试使用 Visual Studio 的调试器来了解为什么我不能正确调用它,但遗憾的是没有希望。 奇怪的是,如果构造函数中的 while 循环不存在,该函数也能正常工作。

这是因为在getline(cin, _name)中,它总是在您键入回车时输入“/n”字符。

要更正它,请输入 getchar();

void PC::changeName()
{
    string _name;
    getchar();
    getline(cin, _name);
    name = _name;
}

您需要在调用 changeName() 之前刷新 cin,这可以使用

来完成
int c;
while ((c = getchar()) != '\n' && c != EOF);