有哪些有效的方法来处理用户键盘输入

时间:2009-07-05 15:17:19

标签: c++

我已经学习了大约一个月的C ++,而且当我编写程序时,我注意到让用户取消输入(在cin循环期间)是一件痛苦的事。例如,一个接受用户输入并将其存储在向量中的程序将具有这样的cin循环。

    vector<int>reftest;
    int number;
    cout << "Input numbers for your vector.\n";
    while(cin >> number)
              reftest.push_back(number);

理想情况是用户只需按Enter键,程序就可以退出循环,但由于没有读取空格,我不知道如何处理。相反,丑陋的东西通常最终会告诉用户输入某个字符来取消他们的输入。

您是否有任何特定方法可用于处理用户输入?

3 个答案:

答案 0 :(得分:3)

有几种方法可以解决您的问题。最简单的可能是移出直接的cin / cout循环并改为使用std :: getline。具体来说,你可以这样写:

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main( int argc, char **argv )
{
  vector<int> reftest;

  while ( true )
  {
    string input;
    getline( cin, input );

    // You can do whatever processing you need to do
    // including checking for special values or whatever
    // right here.

    if ( input.size() == 0 ) // empty input string
    {
      cout << "Assuming you're bored with the Entering Numbers game." << endl;
      break;
    }
    else
    {
      int value;
      // Instead of using the input stream to get integers, we 
      // used the input stream to get strings, which we turn 
      // into integers like this:

      istringstream iss ( input ); 
      while ( iss >> value )
      {
        reftest.push_back( value );
        cout << "Inserting value: " << value << endl;
      }
    }
  }
}

其他方法包括cin.getline()(我不是很喜欢它,因为它适用于char *而不是字符串),使用cin.fail()位来判断传入的值是否为任何好的等等。根据您的环境,可能有许多更丰富的方式来获取用户输入而不是通过iostreams。但这应该指向您所需的信息。

答案 1 :(得分:0)

如何制作第二个循环:

char option;
do
{
    cout << "do you want to input another number? (y)es/(n)o..." << endl;
    cin >> option;
    if ( option == 'y' )
        acceptInput(); // here enter whatever code you need
}
while ( option != 'n' );

答案 2 :(得分:0)

我担心这样做没有好办法。真实世界的交互式程序根本不使用流的格式化(或未格式化,来到那里)输入来读取键盘 - 它们使用特定于操作系统的方法。

相关问题