木其网络科技专业程序员代写http://www.xmsydw.com
程序员学历擅长经验网店链接
apenny硕士ASP.NET PHP 电子 通信设计 图像 编程 网络5年进入店铺
zheng_qianqian本科C语言 C++面向对象 Java3年进入店铺
guoguanl本科Java Web项目 JSP Hibernate Struts Mysql4年进入店铺

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

至此,问题解决。


posted @ 2013-05-17 20:10  C语言程序  阅读(808)  评论(0编辑  收藏  举报
木其网络科技专业程序员代写http://www.xmsydw.com
程序员学历擅长经验网店链接
apenny硕士ASP.NET PHP 电子 通信设计 图像 编程 网络5年进入店铺
zheng_qianqian本科C语言 C++面向对象 Java3年进入店铺
guoguanl本科Java Web项目 JSP Hibernate Struts Mysql4年进入店铺