为什么系统( "CLS" ) 在 while 中不起作用?

Why system("CLS") in while is not working?

本文关键字:while 不起作用 系统 CLS 为什么      更新时间:2023-10-16

我想在选择选项后清除屏幕,但我不知道它不起作用。它将显示Display()函数中的内容以及创建新购买和其他东西。这是因为在循环中?

while (selection != -1) // While for create new purchase 
        {
            cout << "Create New Purhcase" << endl << endl;
            cout << "1. Display Item" << endl;
            cout << "2. Create a New Purchase" << endl << endl <<endl;
            cout << "0. Back to Main Menu" << endl; 
            cout << "Enter Option:";
            cin >> selection;
            //Back to main menu 
            if (selection == 0)
            {
                system("CLS");
                break;
            }
            if (selection == 1)
            {
                system("CLS");
                cout << "Display Menu" << endl;
                Display();
            }
void Display()
{
system("CLS");
temp = itemHead; //start at the first node
cout << "Dispaly Menu" << endl << endl; 
while (temp != NULL)
{
    cout << "ID:" << temp->itemid << endl; 
    cout << "Item Name:" << temp->name << endl;
    cout << "Item Type:" << temp->type << endl;
    cout << "Item Price" << temp->cost << endl;
    cout << endl << endl;
    temp = temp->next; //forward to the next node
}

}

这里的问题是,您的代码在打印Display()函数后不会停止,因为它是While循环的一部分。结果,它打印了菜单,然后继续打印选项。

要确保打印菜单后循环暂停,请将您的代码更改为:

if (selection == 1)
{
    system("CLS");
    cout << "Display Menu" << endl;
    Display();
    cout << endl << endl;
    system("pause");
}

system("pause")也是算法文件的一部分,因此您无需包含任何内容。这样,整个菜单将从您的Display()函数,然后是一些新线来打印,最后是按Enter键的提示。直到您击中Enter键,while循环将不会继续。

注意:还有其他方法可以做到,但这是最简单和最短的方法。如果您对我的答案有任何疑问,或者我的答案不起作用,请在评论框中通知我。