· std::cin.getline()输入缓冲区溢出错误
#include <iostream>
#include "ace/OS.h"
#include "SystemCommon.h"
int main(int argc, char **argv)
{
std::cout << "Hello world!" << std::endl;
TCHAR cmd[COMMONSERVER::COMMAND_BUFFER_SIZE];
while (true)
{
ACE_OS::memset((void *)cmd, 0, sizeof(TCHAR)*COMMONSERVER::COMMAND_BUFFER_SIZE);
std::cin.getline(cmd, COMMONSERVER::COMMAND_BUFFER_SIZE);
std::cout << cmd << std::endl;
}
return 0;
}
现象:在这里出现的输入缓冲区溢出后即出现了死循环。
原因:因为当输入缓冲区溢出后,std::cin将会出现异常,从而std::cin.getline不再等待用户输入之后再执行下面的操作。
解决办法:
1 当出现缓冲区溢出时退出程序,以免出现死循环的情形。如:
#include <iostream>
#include "ace/OS.h"
#include "SystemCommon.h"
int main(int argc, char **argv)
{
std::cout << "Hello world!" << std::endl;
TCHAR cmd[COMMONSERVER::COMMAND_BUFFER_SIZE];
while (true)
{
ACE_OS::memset((void *)cmd, 0, sizeof(TCHAR)*COMMONSERVER::COMMAND_BUFFER_SIZE);
std::cin.getline(cmd, COMMONSERVER::COMMAND_BUFFER_SIZE);
if(!std::cin)
{
std::cerr << "std::cin occur error, perhaps the buffer is overflowed." << std::endl;
break;
}
else
{
std::cout << cmd << std::endl;
}
}
return 0;
}
2 在出现缓冲区溢出后,重置std::cin后,并将缓冲区进行加大分配,可以采用2^n策略进行处理
#include <iostream>
#include <string>
#include "ace/OS.h"
#include "SystemCommon.h"
int main(int argc, char **argv)
{
std::cout << "Hello world!" << std::endl;
int nBufSize = COMMONSERVER::COMMAND_BUFFER_SIZE;
TCHAR *pCmd = new TCHAR[nBufSize];
while (true)
{
ACE_OS::memset((void *)pCmd, 0, sizeof(TCHAR)*nBufSize);
std::cin.getline(pCmd, nBufSize);
if(!std::cin)
{
std::cerr << "std::cin occur error, perhaps the buffer is overflowed." << std::endl;
delete[] pCmd;
nBufSize *= 2;
pCmd = new TCHAR[nBufSize];
std::cin.clear(); // 清除错误标志位
std::cin.sync(); // 清除流
std::cout << "std::cin clear, buffer size is " << nBufSize << std::endl;
}
else
{
std::cout << pCmd << std::endl;
}
}
delete[] pCmd;
// std::string cmd;
// while (true)
// {
// std::getline(std::cin, cmd);
// std::cout << cmd << std::endl;
// }
return 0;
}