overloading istream

overloading istream

本文关键字:istream overloading      更新时间:2023-10-16

我已经重载了>>为我的myString类。但是,当我使用cin >> temp之后,我为字符串使用另一个cin时,似乎其他cin不像以前那样工作。如果你看一下我的代码,我的意思是程序最终不理解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;
}

This is main

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

(基于使用cin和http://www.cplusplus.com/forum/beginner/9148/获取用户输入的答案)