检查istream中是否有待处理数据的简单方法

Easy way to check whether there is data pending in istream

是否有任何标准的非读取方式来检查输入流中是否有待处理的字符?我总是可以尝试

char buffer[256];
std::cin.get(buffer, 256, '\n');
if (!std::cin.fail()) {
// use buffer
}

但它谴责我使用 ios 标志,使用 C 字符串等等。有没有更简单、更清洁的方法来做到这一点?像这样:

if (std::cin.has_data()) {
    std::string data;
    std::getline(std::cin, data);
    // do my stuff
} 

函数peek就是解。

正如 cppreference 所说:

If good() == true, returns the next character as obtained by rdbuf()->sgetc()

Otherwise, returns Traits::eof().