2017-09-13 166 views
0

我想在用户输入后直接添加百分号(以便用户不必输入百分号)。当我尝试这个时,它要么到达下一个线路,要么根本不工作。如何在C++后直接添加字符(cin)

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

对不起,如果这是混乱的,我不知道如何添加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... 

那么,它甚至有可能做我想要什么?

+0

这是不可能的(或可取的)。而iostream库并非真正用于交互式使用。 –

+0

很好,这正是我们在学校学习的内容,所以我想让自己对我自己的用户友好,我猜... – hannacreed

+0

不要浪费你的时间 - 这是不能做到的。 –

回答

0

这绝对是可能的,但iostream并没有真正提供一个适当的接口来执行它。通常对控制台io实现更好的控制需要使用一些平台特定的功能。在VS上,这可以用_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); 
}