【问题标题】:overloading istream重载 istream
【发布时间】:2013-04-02 06:49:09
【问题描述】:

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

【问题讨论】:

  • “不起作用”可能意味着很多事情。请提供更多信息!
  • 如果你总是要将temp的大小设置为1000,为什么要动态分配呢?
  • 您是否在调试器中单步调试过您的代码?看到它在您的输入运算符中读取了所有内容吗?看到getline 调用的输入了吗?
  • 有人告诉我这是this
  • 我已编辑。插入工作正常,但之后我的程序不会中断'n'输入的while循环

标签: c++ overloading


【解决方案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/回答)

【讨论】:

  • getline 用于字符串类,我不想用它:)
  • 好的...但是您已经在 main 函数的 while 循环中使用它...? :)
  • 是的,main.cpp 适用于我的所有程序。我正在编写一个名为 myString 的类,例如字符串类,我希望它在所有情况下都能正常工作!你知道像ignore for cin这样的东西吗?我的意思是我们可以忽略函数中的 \n 吗?
  • 当然! stackoverflow.com/questions/5131647/…(只需查看已接受的答案即可了解如何使用它)
  • 谢谢!还有一个问题,有没有办法用 cin 获得空格?我知道我可以使用 getline,但我不想使用字符串类:D
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 2013-10-10
  • 2011-09-23
  • 1970-01-01
  • 2020-02-10
  • 2021-11-19
  • 1970-01-01
  • 2021-08-07
相关资源
最近更新 更多