c++输入,直到通过键盘发出输入信号结束

c++ input till end of input signalled through keyboard

本文关键字:输入 盘发 结束 键盘 信号 c++      更新时间:2023-10-16

我想写一个C++(C,如果它能为我的问题提供简单的解决方案的话)程序,在这个程序中,一个人可以输入,直到他选择通过按下Ctrl+D这样的按钮组合来发出输入结束的信号。我对此有两个问题。

  1. 哪个组合键用于在Xterm中发出输入结束的信号?(Ctrl+C或Z不起作用)
  2. 当按下1中回答的组合键时,我的while()循环中的逻辑代码应该是什么?

    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

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;
  }
}

使用istream_iterator

等待EOF 的默认构造函数

即窗口上的Ctrl+ZF6+ENTER

linux 上的Ctrl+D

我会使用一个代理类在飞行中插入到地图中,如下所示:

#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;
}