2009-07-05 65 views
1

我已经学习C++大约一个月了,并且正如我编写的程序,我注意到使用户可以取消它们的输入(在cin循环期间)是一种痛苦。例如,一个接受用户输入并将其存储在向量中的程序将具有这样的cin循环。什么是一些有效的方法来处理用户的键盘输入

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

理想的做法是,用户只需按enter键,并为程序退出循环,但由于空白是没有读过我不知道如何做到这一点的处理。相反,丑陋的东西通常最终会告诉用户输入某个字符来取消输入。

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

回答

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()(这我不是的,因为它的工作原理的*不是字符串的字符的大风扇),使用cin.fail( )位以确定传入值是否有好处等。根据您的环境,获取用户输入的方式可能比通过iostream更丰富。但是这应该指向你所需要的信息。

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'); 
+0

我宁愿用户能够简单地输入他们的所有号码,而不是在每次输入后要求更多。 – Alex 2009-07-05 18:17:18

0

恐怕没有这样做的好方法。现实世界的交互式程序根本不使用格式化(或未格式化,来自该流)的输入来读取键盘 - 它们使用特定于操作系统的方法。

相关问题