首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重载istream

重载istream
EN

Stack Overflow用户
提问于 2013-04-02 14:49:10
回答 1查看 511关注 0票数 1

我为我的myString类重载了>>。但是,当我使用cin >> temp之后,我使用另一个cin作为字符串,似乎其他cin不像以前那样工作。如果您查看我的代码,我的意思是程序最终不理解y或n,并且总是在while循环中。

这是istream函数( myString类的朋友)

代码语言:javascript
复制
std::istream &operator>> (std::istream& input, myString& str) {
    char* temp = new char [1000];
    input >> temp;
    int i=0;
    int pow2=1;
    for (i; temp[i]!=NULL; i++) {       
        while(pow2<=i)
            pow2 *= 2;
    }
    delete [] str.string_;
    str.length = i;
    str.capacity = pow2;
    str.string_ = new char [pow2];

    for (int i=0; i<str.length; i++)
        str.string_[i] = temp[i];

    delete [] temp;

    return input;
}

这是main

代码语言:javascript
复制
cout << "myString Program" << endl;
    while(1) { //simple again or not while
        myString c;
        cin >> c;
        cout << c;

        string input;
        cout << "\nCountine (y/n)?";
        getline(cin, input);
        if (input[0] == 'n' || input[0] == 'N')
            break;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-02 15:00:02

代码语言:javascript
复制
std::istream &operator>> (std::istream& input, myString& str) {
    char temp[1000];
    cin.get(temp, 1000); //get all chars until (but not including) the next newline. Expects a size equal to the buffer used to store the chars.
    cin.ignore(); //ignore the next newline character

    int i=0;
    int pow2=1;
    for (i; i < strlen(tmp); i++) {       
        while(pow2<=i)
            pow2 *= 2;
    }
//...

(答案基于Getting input from user using cinhttp://www.cplusplus.com/forum/beginner/9148/)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15757860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档