'How to get the number of strings stored in a stringstream

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?



Solution 1:[1]

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.

Solution 2:[2]

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 >( ) );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SoronelHaetir
Solution 2