开发者

A C++ Equivalent to PHP's fgets()?

开发者 https://www.devze.com 2023-01-21 07:34 出处:网络
Essentially what I\'m looking for is a function with the following prototype: string getln(istream); All I need it to do is work like PHP\'s fgets(), that开发者_JAVA技巧 is, take an input stream as a

Essentially what I'm looking for is a function with the following prototype: string getln(istream);

All I need it to do is work like PHP's 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 (like some_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消