2013-07-28 136 views
0

我想寫一個C++(如果它提供了簡單的解決方案,我的問題)程序,其中可以輸入,直到他選擇信號結束輸入通過按這樣的組合按鈕作爲Ctrl + D。我有兩個關於這個問題。C++直到輸入結束通過鍵盤輸入信號

  1. 哪個鍵組合(一個或多個)被用來/到信號輸入在的Xterm的端? (Ctrl + C或Z不起作用)
  2. 當我在while()循環中按邏輯代碼進行相應處理時,如果按下組合鍵1時回答爲1,那麼該邏輯代碼應該如何處理?當從終端接收輸入信號的結束

    map<int,string>info; 
    string name; 
    int age; 
    cin>>name; 
    while(?????????){ //Input till EOF , missing logic 
        cin>>age; 
        info.insert(pair<int,string>(age,name)); 
        cin>>name; 
    } 
    //sorted o/p in reverse order 
    map<int,string> :: iterator i; 
    for(i=info.end(); i !=info.begin(); i--) 
        cout<<(*i).second<<endl; 
    cout<<(*i).second<<endl; 
    

    }

程序繼續。我使用gcc/g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

回答

0

while條件應該是這樣的:

while(the_key_combination_pressed_in_the_last_loop!=what_combination_will_exit_while) 
{ 
    cin>>age; 
    if(age!=what_combination_will_exit_while) 
    { 
     info.insert(pair<int,string>(age,name)); 
     cin>>name; 
    } 
} 
0

使用istream_iterator

默認的構造函數的等待EOF

Ctrl+ZF6+ENTER在Windows

Ctrl+D上linux

我會使用一個代理類插入到地圖上的蒼蠅,類似如下:

#include <map> 
#include <iterator> 
#include <algorithm> 
#include <string> 
#include <functional> 
#include <iostream> 

template<class Pair> 
class info_reader // Proxy class, for overloaded << operator 
{ 
public: 
     typedef Pair pair_type; 

     friend std::istream& operator>>(std::istream& is, info_reader& p) 
     { 
       return is >> p.m_p.first >> p.m_p.second; 
     } 

     pair_type const& to_pair() const 
     { 
       return m_p; //Access the data member 
     } 
private: 
     pair_type m_p;     
}; 


int main() 
{ 
    typedef std::map<int, std::string> info_map; 

    info_map info; 
    typedef info_reader<std::pair<int, std::string> > info_p; 

     // I used transform to directly read from std::cin and put into map 
     std::transform(
      std::istream_iterator<info_p>(std::cin), 
      std::istream_iterator<info_p>(), 
      std::inserter(info, info.end()), 
      std::mem_fun_ref(&info_p::to_pair) //Inserter function 
       ); 

//Display map 
for(info_map::iterator x=info.begin();x!=info.end();x++) 
    std::cout<<x->first<< " "<<x->second<<std::endl; 
} 
+0

插入地圖本來就不大對我的關注。我想要一個像'while(cin >> name){...}'這樣的C++邏輯smthng,只要按下_Key-Combination_就會停止對輸入進行處理。但顯然這是行不通的。所以建議我一些其他的方法。 – KNU

+0

@KunalKrishna上面的代碼可以使用Ctrl + D(linux)或Ctrl + Z 你想要其他的組合鍵嗎? – P0W

+0

@POW我得到了第一部分和關鍵組合的答案。但是我很難實施它。問題是使用一個相同的構造,如果它是字符串,那麼我必須做任何事情,如果它的組合鍵是** exit **。 – KNU