I have some following code. In order to limit call times of operator << to std::cout
. I use an std::ostream outside forloop. But I get compile errors.
- source code shows:
#include <iostream>
int square(int num) {
std::ostream os;
for (int i=0; i<10; i++) {
os << "test: i," << std::endl;
}
std::cout << os;
return 0;
}
- error shows:
In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/iostream:39:0,
from <source>:2:
/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ostream: In function 'int square(int)':
/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ostream:384:7: error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits<char>]' is protected
basic_ostream()
^
<source>:6:18: error: within this context
std::ostream os;
^
Compiler returned: 1
Does the smart code with efficiency exist?
Let me make my intension clear.
I don't want to call api and write date to std::cout by multiple times in a loop. I know that I can use a string buffer to receive data multiple times, and finally print to std::cout. But this also takes the cost of creating a string. Is there any directly use of the api or structure provided by <iostream> to write better code?