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

前端 未结 8 866
粉色の甜心
粉色の甜心 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 08:54

    I know that this question is very old and already answered, but depending on the situation there might also be yet another approach worth considering:

    When you are testing if a stringstream is empty, you properly intend to do something with either the individual strings or each line in the stringstream; thus you will most likely be using either the >> operator or std::getline on the stringstream... and if the stream is empty these simply have the value false, thus you could write:

    stringstream report_string;
    
    foo(report_string)// some functions which may or may not write to report_string
    
    string single_report;//string to read to
    
    bool empty=true;//First assume it was empty
    while(getline(report_string,single_report))//Alternatively use report_string>>single_report if you don't want entire lines
    {
        empty=false;//...it wasn't empty
        bar(single_report);//Do whatever you want to do with each individual appended line 
    }
    
    if (empty)
    {
        //... whatever you want to do if the stream was empty goes here
    }
    

    It should be noted that this approach assumes that you were planning on cycling through the stringstream; if you were not, then this approach can't be used.

提交回复
热议问题