如何从cin中清除多余的字符?

Tho*_*s B 1 c++ iostream

char buff[3];

cout<<"From: ";
cin.getline(buff, 3);

//something something

cout<<"To: ";
cin.getline(buff, 3);
Run Code Online (Sandbox Code Playgroud)

如何在评论中清除缓冲区,以便额外的字符不会出现在我的第二个cin

tem*_*def 5

一种方法是使用istream::ignore:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)

这将跳过最大可能的字符数,直到读取换行符.

但是,对于它的价值,您可能不应该使用istream::getline它,因为它适用于原始C风格的字符串.更好的选择是使用std::string和自由功能std::getline:

std::string buffer;
getline(cin, buffer);
Run Code Online (Sandbox Code Playgroud)

这将自动读取所有字符,stdin直到换行.