c++输入,直到通过键盘发出输入信号结束
c++ input till end of input signalled through keyboard
我想写一个C++(C,如果它能为我的问题提供简单的解决方案的话)程序,在这个程序中,一个人可以输入,直到他选择通过按下Ctrl+D这样的按钮组合来发出输入结束的信号。我对此有两个问题。
- 哪个组合键用于在Xterm中发出输入结束的信号?(Ctrl+C或Z不起作用)
-
当按下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+Z
或F6+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;
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type