while(cin >> buf)在linux下实现停止输入的办法
2013-05-17 20:10
447 查看
问题:
ubuntu下编写测试下标运算符[]重载的程序。使用while (cin >> buf)将接收到的字符串存储到string buf中,不知道该怎样结束cin的输入操作;
解决办法:
1. 放狗搜,结论是linux下使用Ctrl+d,windows下使用Ctrl+z来结束键盘输入。源程序如下:
#include <iostream> #include <vector> using namespace std; class Assoc { struct Pair { string name; double val; Pair (string n = "", double v=0) : name(n),val(v) {} }; vector<Pair> vec; Assoc(const Assoc&); Assoc& operator=(const Assoc&); public: Assoc() { // vector<Pair> vec(1); } Assoc(int i) { for (int cj=0; cj<i; ++cj) { // vector<Pair> vec(i); vec.push_back(Pair("", cj)); } } double& operator[] (string&); void print_all() const; const int size() const; }; double& Assoc::operator[](string& s) { // Search s; return its value if found, else return a new pair for (vector<Pair>::const_iterator p = vec.begin(); p != vec.end(); ++p) { if (s == p->name) { return (double&)p->val; } else { } } vec.push_back(Pair(s, 0)); return vec.back().val; } void Assoc::print_all() const { for (vector<Pair>::const_iterator p=vec.begin(); p != vec.end(); ++p) { cout << p->name << " : " << p->val << endl; } } const int Assoc::size() const { return vec.size(); } int main() { string buf; Assoc v1; while(cin >> buf) { v1[buf]++; } cout << "v1 size: " << v1.size() << endl; v1.print_all(); return 0; }
编译完成,运行程序。
程序的功能是从键盘接受输入的字符串,统计不同字符串的输入次数。
david@ubuntu:~/wrk/tmp/cpp_exer$ ./test_subscriptor_reload boy boy boy cat cat dog v1 size: 3 boy : 3 cat : 2 dog : 1使用Ctrl+D的方式结束从cin继续输入字符串。
至此,问题解决。
相关文章推荐
- while(cin >> buf)在linux下实现停止输入的办法
- linux下设定动态库路径的命令->error while loading shared libraries: xxx.so.x"错误的原因和解决办法
- 关于while(cin>>str)输入无法结束的问题(转+修改)
- linux 关于while((n=read(STDIN_FILENO,buf,BUFFSIZE)) > 0)
- 标准输入cin的返回值以及while(cin>>x)的问题
- while(cin >>)的输入停止与错误问题
- 关于while(std::cin>>value)
- while(cin>>str)无法结束的问题
- while(scanf("%d",&n)!=EOF)与while(cin>>n)
- while(cin>>word){}如何停止的正确做法,而不是 Ctrl+Z或 Ctrl+D强制结束
- while(cin>>str)无法结束的问题
- 血淋淋的教训:输入数据有多组:所以一定要while(cin>>str){}
- while(cin>>val)的调用机理
- 如何退出while(cin>>value)的循环
- while (cin>>str)退出死循环
- c++学习笔记—while(cin>>ival)
- 实现cin>>complex
- 第九周试验任务1--定义Time类中的<<和>>运算符的重载,实现输入和输出。
- while(cin>>something)
- if(cin) while(cin) 以及 while(cin>>x) 条件表达式中的 流对象cin 的用法