Home > Mobile >  How to get the number of strings stored in a stringstream
How to get the number of strings stored in a stringstream

Time:03-05

I need to test to see if the number of extracted strings from a string_view is equal to a specific number (e.g. 4) and then execute some code.

This is how I do it:

#include <iostream>
#include <iomanip>
#include <utility>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include <iterator>


int main( )
{
    const std::string_view sv { "   a 345353d&  ) " }; // a sample string literal

    std::stringstream ss;
    ss << sv;

    std::vector< std::string > foundTokens { std::istream_iterator< std::string >( ss ),
                                             std::istream_iterator< std::string >( ) };

    if ( foundTokens.size( ) == 4 )
    {
        // do some stuff here
    }

    for ( const auto& elem : foundTokens )
    {
        std::cout << std::quoted( elem ) << '\n';
    }
}

As can be seen, one of the downsides of the above code is that if the count is not equal to 4 then it means that the construction of foundTokens was totally wasteful because it won't be used later on in the code.

Is there a way to check the number of std::strings stored in ss and then if it is equal to a certain number, construct the vector?

CodePudding user response:

NO, a stringstream internally is just a sequence of characters, it has no knowledge of what structure the contained data may have. You could iterate the stringstream first and discover that structure but that wouldn't be any more efficient than simply extracting the strings.

CodePudding user response:

You can do it something like the following

    #include <iterator>

    //...

    std::istringstream is( ss.str() );
    auto n = std::distance( std::istream_iterator< std::string >( is ),
        std::istream_iterator< std::string >() );

After that comparing the value of the variable n you can decide whether to create the vector or not.

For example

std::vector< std::string > foundTokens;

if ( n == 4 ) foundTokens.assign( std::istream_iterator< std::string >( ss ), std::istream_iterator< std::string >( ) );
  • Related