如何在c ++中直接添加char(cin)

时间:2017-09-13 19:34:08

标签: c++ windows visual-studio window

我试图在用户输入后直接添加百分号(这样用户就不必键入百分号)。当我尝试这个时,它要么转到下一行,要么根本不起作用。

我想要的是什么: _%
//空白用于用户的输入。

对不起,如果这很麻烦,我不知道如何在这里添加c ++。

以下是我尝试过的一些事情:

// used a percent as a variable:
const char percent = '%';

cout << "Enter the tax rate: " << percent; // obviously here the percent 
symbol goes before the number. 

double taxRate = 0.0;
cin >> taxRate >> percent; // here I tried adding it into the cin after the cin.

cin >> taxRate >> '%'; // here I tried adding the char itself, but yet another failed attempt...

那么,甚至可以做我想要的事情吗?

1 个答案:

答案 0 :(得分:0)

绝对有可能,但是iostream并没有真正提供适当的界面来执行它。通常,实现对控制台io的更大控制需要使用一些特定于平台的功能。在带VS的Windows上,这可以使用_getch完成,如下所示:

#include <iostream>
#include <string>
#include <conio.h>
#include <iso646.h>

int main()
{
    ::std::string accum{};
    bool loop{true};
    do
    {
        char const c{static_cast<char>(::_getch())};
        switch(c)
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            {
                //  TODO limit accumullated chars count...
                accum.push_back(c);
                ::std::cout << c << "%" "\b" << ::std::flush;
                break;
            }
            case 'q':
            {
                loop = false;
                accum.clear();
                break;
            }
            case '\r': // Enter pressed
            {
                //  TODO convert accumullated chars to number...
                ::std::cout << "\r" "Number set to " << accum << "%" "\r" "\n" << ::std::flush;
                accum.clear();
                break;
            }
            default: // Something else pressed.
            {
                loop = false;
                accum.clear();
                ::std::cout << "\r" "oops!!                              " "\r" << ::std::flush;
                break;
            }
        }
    }
    while(loop);
    ::std::cout << "done" << ::std::endl;
    return(0);
}