从istream输入一次读取一个字符

时间:2015-01-13 04:29:12

标签: c++ insert overloading

此代码应该使用自定义数据结构(堆栈类型)作为数组或STL容器的替代来存储非常长的用户类型数字。我正试图超载>>运营商这样

LongInt int1;
cin>>int1;

会奏效。

我的代码:

istream& operator>> (istream& input, LongInt& number) //class name is LongInt
{
    char c;
    int a;
    while (input>>c){ // read one number at a time
        a=c-'0'; // converting the value to int
        number.stackli.push(a); // pushing the int to the custom stack
    }

    return input;
}

应该在用户输入他的号码并按下回车后终止,但是会导致无限循环。注释循环内的两行仍会导致无限循环。任何有关如何解决此问题的建议都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

只要(input >> c)处于true状态,input始终为good,例如,未关闭,因此无限循环。

即使您没有任何输入,循环也会被阻止"而不是"结束"。

要仅使用输入流中的一部分而不是整体,您需要以下内容:

while(input >> c) {
    if(c<='0' || c>='9') {
        // "c" is not the character you want, put it back and the loop ends
        input.putback(c); break;
    }
    ...
}