2009-07-05 60 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

恐怕沒有這樣做的好方法。現實世界的交互式程序根本不使用格式化(或未格式化,來自該流)的輸入來讀取鍵盤 - 它們使用特定於操作系統的方法。

相關問題