【问题标题】:Editable Console Output可编辑的控制台输出
【发布时间】:2011-09-27 11:57:49
【问题描述】:

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

//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!

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

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

【问题讨论】:

  • conio 应该有移动光标的功能。试试:gotoxy (int x, int y)
  • 在标签中添加了conio,因为我错过了您已经在使用此库的情况 - 重新标记可能有助于找到 conio 专家(并避免像我这样的 ncurses 答案(现已删除))。

标签: c++ console conio


【解决方案1】:

这个这个:

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

这不是完全您想要的,但它是最接近的,只需最少的返工。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    相关资源
    最近更新 更多