Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 << "some string here..."; 

In my code itself are various conditions for assigning values to the report_string variable.

I'd like to check whether it was assigned a value or not.

like image 231
cr8ivecodesmith Avatar asked Nov 08 '11 05:11

cr8ivecodesmith


People also ask

How do you check if a Stringstream is empty?

readsome(&test_char, 1) == 0 to confirm it is empty. Also looking at my_stream. tellp() == 0, what about my_stream. tellg()>=mystream.

How do you clear a Stringstream variable?

For clearing the contents of a stringstream , using: m. str("");

Does Stringstream allocate?

stringstream is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated. dummy is then cleared and then erased, freeing up its allocation.

What is Istringstream C++?

What Is the StringStream Class? The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.


2 Answers

myStream.rdbuf()->in_avail() can be used to get the count of available characters ready to be read in from a stringstream, you can use that to check if your stringstream is "empty." I'm assuming you're not actually trying to check for the value null.

For example if you want to extract an int from a stringstream and then see if there were any left over characters (ie. non-numeric) you could check if myStream.rdbuf()->in_avail() == 0.

Is that something similar to what you're trying to do? I'm not sure if there's better ways but I've done this in the past and it's worked fine for me.

https://en.cppreference.com/w/cpp/io/basic_streambuf/in_avail

EDIT: I see you just updated your question as I posted.

like image 56
AusCBloke Avatar answered Oct 07 '22 09:10

AusCBloke


An easy check would be to see if the string content of the stream is empty or not:

#include<assert.h> #include<sstream>  int main(){ std::stringstream report_string; report_string << ""; // an empty strin g  //emptiness check of stringstream assert(report_string.str().empty()); } 
like image 39
SvSharma Avatar answered Oct 07 '22 08:10

SvSharma