lcdavis13
lcdavis13

Reputation: 119

C++ stringstream: Extracting consistently, regardless of whether the string ends with whitespace?

What's the simplest way to extract an unknown number of items from a std::stringstream, that behaves consistently regardless of whether the string has whitespace at the end?

Here's an example that tests two slightly different methods, to show what I mean:

#include <cstdio>
#include <sstream>
#include <vector>
using namespace std;

void parse1(const char* text)
{
    stringstream text_stream(text);
    vector<string> string_vec;
    char temp[10];

    while (text_stream.good())
    {
        text_stream >> temp;
        printf("%s ", temp);
        string_vec.push_back(temp);
    }
    printf("\n");
}

void parse2(const char* text)
{
    stringstream text_stream(text);
    vector<string> string_vec;
    char temp[10];

    while (text_stream.good())
    {
        text_stream >> temp;
        if (text_stream.good()) 
        {
            printf("%s ", temp);
            string_vec.push_back(temp);
        }
    }
    printf("\n");
}

int main()
{
    char text1[10] = "1 2 3 ";
    char text2[10] = "1 2 3";

    printf("\nMethod 1:\n");
    parse1(text1);
    parse1(text2);

    printf("\nMethod 2:\n");
    parse2(text1);
    parse2(text2);
}

This code produces the following output. Notice that the each of them messes up in one of the two situations:

Method 1:
1 2 3 3
1 2 3

Method 2:
1 2 3
1 2

Upvotes: 0

Views: 113

Answers (2)

LogicStuff
LogicStuff

Reputation: 19627

In your loop conditions, you are checking for errors in the stream, before you try to read anything:

while(text_stream.good())
{
    text_stream >> temp;
    printf("%s ", temp);
    string_vec.push_back(temp);
}

It should be done in the reverse order. Idiomatically, like this:

// read to temp, then use operator bool() to get whether an error has occurred
while(text_stream >> temp)
{
    printf("%s ", temp);
    string_vec.push_back(temp);
}

There's no need to talk about the second version, it's based on the same error.

Upvotes: 1

SHR
SHR

Reputation: 8333

try this:

 void parse3(const std::string& text)
 {
   std::vector<std::string> string_vec;
   std::stringstream text_stream(text); 
   std::string temp;
   while ( text_stream >> temp)
   {
     std::cout<<temp<<" ";
     string_vec.push_back(temp);
   }
   std::cout<<std::endl; 
 } 

Upvotes: 0

Related Questions