How do I check if a StringStream variable is empty/null?

前端 未结 8 868
粉色の甜心
粉色の甜心 2020-12-13 08:32

Just a quick question here guys. I\'ve been searching to no avail so far.

A bit more info here:

stringstream report_string;

report_string << \         


        
8条回答
  •  孤城傲影
    2020-12-13 09:19

    It's normally reasonable and readable to use...

    report_string.str().empty()
    

    ...but that may involve dynamic allocation and copying the entire string to a temporary, only to be thrown away.

    If performance is important, another option is...

    report_string.peek() == decltype(report_string)::traits_type::eof()
    
    • this looks for a character not yet extracted from the stream, ignoring input that's already been successfully parsed/extracted

      • that's different from testing report_string.str().empty(), which still "sees" already-extracted input
    • if earlier parsing left the stream in a fail state you haven't clear()ed, this will return eof() regardless of whether there are more unextracted characters

提交回复
热议问题