开发者

Editable Console Output

开发者 https://www.devze.com 2023-04-07 17:27 出处:网络
Here is a portion of some code I am trying to write: //Choice Based Menu #include <iostream.h> #include <conio.h>

Here is a portion of some code I am trying to write:

//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;
 开发者_JAVA百科           }
        }

    }while(1);
}

Since the loop continues indefinitely, it waits for another input option after executing the code of the previously chosen option.

Menu

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

Choice: A
Option A!

I want the line "Choice: A" to update with the most recently entered option every single time. And I want the output of the previously selected option (Option A!) to be replaced with the output from a newly chosen option.

I tried using '\r' as you may have noticed. That does not work because it gives me a carriage return i.e. it moves back to the beginning of the line. I want it to move back only by one character, and not to the beginning of the line.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消