从输入缓冲区读取
Reading from input buffer
void dr1() {
int num1 = 0, num2 = 0;
char str[100];
while (str[0] != '|') {
cout << "Please enter two numbers (enter "|" to terminate): ";
cin >> num1;
cin >> num2;
cin.getline(str, 100);
cout << num1 << num2 << endl;
}
}
如果用户输入字符串,变量不应该str
从输入缓冲区读取它吗?
根据我所学到的知识,您不能将字符串字符输入到int
类型中,因此它们会保留在缓冲区中。如果它们留在缓冲区中,getline()
不应该读取缓冲区中剩余的任何输入吗?
如果operator>>
无法读取格式化的值,则输入确实留在缓冲区中,并且流也进入错误状态,因此后续读取将被忽略并且也失败。这就是为什么getline()
没有按预期读取"|"
输入的原因。您需要在格式化读取操作失败后clear()
流的错误状态。 例如:
void dr1()
{
int num1, num2;
char str[100];
do
{
cout << "Please enter two numbers (enter "|" to terminate): " << flush;
if (cin >> num1)
{
if (cin >> num2)
{
// use numbers as needed...
cout << num1 << num2 << endl;
continue;
}
}
cin.clear();
if (!cin.getline(str, 100)) break;
if (str[0] == '|') break;
}
while (true);
}
相关文章:
- 套接字读取后,我在缓冲区中看到意外输入
- 如何使用带有矢量的 winapi 读取进程内存从另一个进程读取缓冲区?
- 读取缓冲区时访问冲突 UNICODE_STRING
- ifstream 不读取缓冲区
- Unix 读取缓冲区参数
- 从超强的AndroidAudioIO输入读取缓冲区
- C++ / RS232C 串口 / 事件回调异步读取缓冲区 / 不使用线程
- QTCPSOCTED数据传输在读取缓冲区已满时停止,并且在释放时不会恢复
- 读取缓冲区
- 为什么无法使用glReadPixel()读取Z缓冲区
- ClearCommError中的串行通信在读取缓冲区中找不到任何数据
- 提升asio读取缓冲区
- 正在读取缓冲区C/C++
- ostringstream 运算符 [] 在尝试读取缓冲区时给出编译错误
- 为什么boost::asio::读取缓冲区数据大小小于读取大小
- 使用C++AMP读取缓冲区数据
- TCP套接字:传入数据在ack之后(离开TCP读取缓冲区)但在read()/recv()之前的位置
- 我正在尝试尽快逐行读取缓冲区
- 文件io-C++读取缓冲区大小
- 逐字符从管道读取缓冲区/查找管道中数据的大小