How to do "getline" from a std::string?
Asked Answered
N

1

22

I have a problem. I load the whole file and then getline through it to get some info. However in the map format there may be 0 or 20 "lines" with the info. I need to know how to getline through std::string. There is a function (source stream, destination string, decimal) but I need (source string, destination string, decimal). Searching in streams isn't possible in C++ (only using many temp string and extracting and inserting many times, it's unclear and I don't want to do it that messy way). So I want to know how to getline from a std::string.

Thans

Naji answered 12/12, 2012 at 10:48 Comment(0)
S
33

You seem to want std::istringstream, which is in the header <sstream>:

std::string some_string = "...";

std::istringstream iss(some_string);

std::string line;
while (std::getline(iss, line))
{
    // Do something with `line`
}
See answered 12/12, 2012 at 10:50 Comment(6)
Thanks. Simple question related to it. How to make getline NOT to get a line when there is no decimal found in the stream?Naji
Because that's still a problem as I can't search in a stream (that's why I wanted string getline which doesn't exist).Naji
@Naji The simplest is probably to check if the string you use contains a digit, and then skip the whole std::istringstream/std::getline bit.See
Doesn't your second line copies the whole string? It may become a problem if the string is very large (I'm dealing with a 90 MB string right now, and want to know how to do it without this duplication).Menarche
@Menarche Is each line 90MB? Then your data is not suitable for reading as a single line. If you have a file whose size is total 90MB, but the lines themselves are only a few hundred characters, then it's fine. It all depends on the actual data and what you're supposed to do with it, of course.See
Your second line is std::istringstream iss(some_string);, so I meant the whole string is 90 MB. But I already found a solution. Thank you!Menarche

© 2022 - 2024 — McMap. All rights reserved.