Essentially what I'm looking for is a function with the following prototype: string getln(istream);
fgets()
, that开发者_JAVA技巧 is, take an input stream as a parameter and return the next line from the stream.
I feel like my current approach is somewhat bulky for creating a temporary variable each time it's called:
string getln(istream &input) { string rtn; getline(input, rtn); return rtn; }
Are there any better solutions?
Background:
I'm not looking for a function like this for assignment operations (likesome_str = getln(ifile);
) but I'm trying to use it as a data source for a stringstream. Ultimately I want a smaller version of getline(ifile, tmp); string_str.str(tmp);
that looks a bit more like string_str.str(getln(ifile));
but without the overhead of my example function creating a temp variable each time.
If I'm being too picky about this, feel free to call me out on it. I'm just hoping to see if there's a way to improve on my method.
You're being picky. Any function that returns a string is going to have a string variable that's declared, filled, and returned, just like the function you've already written.
Besides, the "named return-value optimization" allows the compiler to elide the extra variable sometimes. The caller will allocate space for the object and pass it to your function, where it will be modified as though it were the rtn
variable; no copy will be made while returning because the value is already in the desired location.
精彩评论