Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I std::find a string in a stringstream?

Tags:

c++

find

std

c++11

I have a stringstream that I'd like to iterate and determine if a substring exists in it.

I know that I could just convert to a string and do std::string::find(), but I was just hoping to avoid the conversion from stringstream to string if possible.

I understand the following won't work because the istream_iterator uses char as its type (not string)

stringstream ssBody;
string sFindThis;

...

auto itr = std::find (
    istreambuf_iterator<char>(ssBody),
    istreambuf_iterator<char>(),
    sFindThis
);

But can I somehow search for a string in stringstream with std::find or similar without a conversion to string?

like image 652
stack user Avatar asked Aug 04 '16 10:08

stack user


People also ask

Is Stringstream deprecated?

The classes in <strstream> are deprecated. Consider using the classes in <sstream> instead.

How do you read a Stringstream in C++?

To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.

Can you use Getline on Stringstream?

You cannot std::getline() a std::stringstream ; only a std::string . Read as a string, then use a stringstream to parse it. Hope this helps. Save this answer.

What does Stringstream in C++ do?

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

The C++ standard does not define any std::[io]?stringstream methods for searching its contents.

Neither can you use std::istreambuf_iterator together with std::search(), since std::istreambuf_iterator is an input iterator, but std::search() requires a forward iterator.

The only effective way to search a string stream is to convert it to a std::string, first.

like image 147
Sam Varshavchik Avatar answered Nov 06 '22 16:11

Sam Varshavchik


using pubsetbuf it is possible to associate a buffer with basic_stringbuf member and then search the buffer, however behavior of this function is implementation defined. explanations and the example are from http://en.cppreference.com/w/cpp/io/basic_stringbuf/setbuf

#include <iostream>
#include <sstream>

int main()
{
    std::ostringstream ss;
    char c[1024] = {};
    ss.rdbuf()->pubsetbuf(c, 1024);
    ss << 3.14 << '\n';
    std::cout << c << '\n';
}
like image 20
rahnema1 Avatar answered Nov 06 '22 15:11

rahnema1