c++ input till end of input signalled through keyboard

1.9k Views Asked by At

I want to write a C++ (C, if it provides easy solution to my problem) program where one may input until he chooses to signal end of input by pressing such combination of buttons as Ctrl+D. I have two questions regarding this.

  1. Which key-combination(s) is/are used to signal the end of input in Xterm? (Ctrl+C or Z didn't work)
  2. What should be the logical code in my while() loop to process accordingly, when one presses the key combination as answered in 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;
    

    }

The program proceeds upon receiving the end of input signal from terminal.

I use gcc/g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3.

2

There are 2 best solutions below

0
On

The while condition should be something like:

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

Use a istream_iterator

The default constructor of which wait for EOF

i.e Ctrl+Z or F6+ENTER on windows

Ctrl+D on linux

I'd use a proxy class to insert into map on the fly, something like as follows:

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