从 istream 输入中一次读取一个字符
Read one character at a time from istream input
此代码应该使用自定义数据结构(堆栈类型)作为数组或 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;
}
...
}
相关文章:
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 从矢量C++读取字符时出现问题
- 从格式化输入操作中获取读取字符数
- 使用 cin.get 读取字符数组
- 按下回车键时,如何使数组停止读取字符
- C++:读取字符是不正确的
- 如何从输入文件中读取字符并将其存储到向量中?
- 线程函数无法从堆上分配的缓冲区中读取字符
- 使用 cin.get() 读取字符
- C++:使用 fgets() 读取字符输入时出错
- C++ 从文件中读取字符,计算每个字符并进行排序
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 逐字读取字符数组,无需字符串函数
- 是否有任何方法可以在用户输入文本时读取字符
- 从字符串中读取字符时出错
- 如何按字符从文件到2D数组读取字符
- 重载>>运算符和读取字符
- 从堆栈中读取字符后,如何修复不正确的文件输出
- 如何从文件中读取“”字符
- 读取字符 * 始终具有相同的地址