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

Read one character at a time from istream input

本文关键字:读取 字符 一个 一次 istream 输入      更新时间:2023-10-16

此代码应该使用自定义数据结构(堆栈类型)作为数组或 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;
}

应在用户键入其号码并按 Enter 后终止,但会导致无限循环。注释掉循环中的两条线仍会导致无限循环。有关如何解决此问题的任何建议将不胜感激。

因为只要input处于good状态(例如,不闭合),(input >> c)就会一直true,因此无限循环。

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

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

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