超载istream

时间:2013-04-02 06:49:10

标签: c++ overloading

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

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

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;
}

这是主要的

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;
    }

1 个答案:

答案 0 :(得分:1)

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/的答案)