• while(cin >> buf)在linux下实现停止输入的办法


    问题:

    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继续输入字符串。

    至此,问题解决。


  • 相关阅读:
    opencv 单应矩阵
    对极约束
    opencv Mat 操作
    两个视角得到世界坐标系
    opencv storage 操作C++
    Python操作mysql数据库
    java——保留一位、两位小数
    数据库 select from 库名 表名 的用法
    python 使用国内镜像下载插件及报错Could not fetch URL https://pypi.org/simple/pywinauto/: There was a problem co解决方法
    pycharm下载第三方库AttributeError: module 'pip' has no attribute 'main'问题解决
  • 原文地址:https://www.cnblogs.com/java20130726/p/3218494.html
Copyright © 2020-2023  润新知