-1

这是我正在尝试编写的一些代码的一部分:

//Choice Based Menu
#include <iostream.h>
#include <conio.h>
int main()
{
    char choice;
    cout<<"Menu"<<endl<<endl;
    cout<<"A. Option A"<<endl;
    cout<<"B. Option B"<<endl;
    cout<<"C. Option C"<<endl;
    cout<<"Q. Quit"<<endl;
    cout<<endl<<"Choice:\t";
    do
    {
        choice=getch();
        cout<<choice<<"\r";
        switch(choice)
        {
            case 'A':
            {
                cout<<endl<<"Option A!";
                break;
            }
            case 'B':
            {
                cout<<endl<<"Option B!";
                break;
            }
            case 'C':
            {
                cout<<endl<<"Option C!";
                break;
            }
            case 'Q':
            {
                return 0;
            }
            default:
            {
                cout<<endl<<"Invalid Choice! Please try again.";
                break;
            }
        }

    }while(1);
}

由于循环无限期地继续,它在执行先前选择的选项的代码后等待另一个输入选项。

Menu

A. Option A
B. Option B
C. Option C
Q. Quit

Choice: A
Option A!

我希望“选择:A”行每次都更新为最近输入的选项。我希望将先前选择的选项(选项 A!)的输出替换为新选择的选项的输出。

正如您可能已经注意到的,我尝试使用 '\r'。这不起作用,因为它给了我一个回车,即它移回到行首。我希望它只向后移动一个字符,而不是移动到行首。

4

1 回答 1

1

This this:

#include <iostream.h>
#include <conio.h>
int main()
{
    char choice;
    cout<<"Menu"<<endl<<endl;
    cout<<"A. Option A"<<endl;
    cout<<"B. Option B"<<endl;
    cout<<"C. Option C"<<endl;
    cout<<"Q. Quit"<<endl;
    do
    {
        choice=getch();
        cout << "\r" << "Choice:\t"; // Moved into the loop
        switch(choice)
        {
            case 'A':
            {
                cout << "Option A!"; // No more endl
                break;
            }
            case 'B':
            {
                cout << "Option B!";
                break;
            }
            case 'C':
            {
                cout << "Option C!";
                break;
            }
            case 'Q':
            {
                return 0;
            }
            default:
            {
                cout << "Invalid Choice! Please try again.";
                break;
            }
        }
    }while(1);
    cout << endl; // New sole endl
}

This is not exactly what you want, but it's the closest one can get with minimal rework.

于 2011-09-27T12:23:40.383 回答