I have a statement like such that is meant to output what the function returns.
std::cout<<"result: " << calculateAvg(someArray, size) << std::endl;
The function however, outputs things itself before it returns the value. Is there a way for me to print out what is returned on that line, instead of after everything that is printed by the function?
Is there a way for me to print out what is returned on that line, instead of after everything that is printed by the function?
No. The function has to run before it can return something. This means any output the function outputs will come before the output of the functions' return value.
You can redirect std::cout to a buffer (see this post), call the function, redirect back, print result and then print the buffer:
#include <iostream>
#include <sstream>
#include <string>
std::string myFunc() {
std::cout << "print inside myFunc" << std::endl;
return "string returned from myFunc";
}
int main() {
std::stringstream print_inside;
std::streambuf * old = std::cout.rdbuf(print_inside.rdbuf());
std::string returned_string = myFunc();
std::cout.rdbuf(old);
std::cout << returned_string << std::endl;
std::cout << print_inside.str() << std::flush; //endl already there
}
Related
This question already has answers here:
Mixing cout and wcout in same program
(6 answers)
Closed 3 years ago.
Having been compiled using g++, the program below prints the std::wcout expression only. But if you uncomment the 8th row, it prints three expressions properly.
I would like to know the cause of such strange behavior.
#include <iostream>
#include <cstring>
#include <boost/format.hpp>
int main () {
int x = 10;
wchar_t str[] = L"Hello, world!";
// std::cout << "what?" << std::endl;
std::wcout << L"str = \"" << str << L"\" | len = " << wcslen(str) << L"\n";
std::cout << boost::format("x = %d | &x = %p") % x % &x << std::endl;
return 0;
}
Quoting from this page
A program should not mix output operations on cout with output operations on wcout (or with other wide-oriented output operations on stdout): Once an output operation has been performed on either, the standard output stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stdout.
The reason it works when you use cout first is because your implementation allows wcout to output to byte-oriented streams. This is not guaranteed for all implementations. As mentioned in the quoted text, the only correct way to switch between them is with freopen like so:
#include <cstdio>
#include <iostream>
int main () {
std::wcout << L"Hello" << std::flush;
freopen(nullptr, "a", stdout);
std::cout << " world\n" << std::flush;
}
But it's probably simpler to just avoid mixing them.
So when I have this function, and I print it to the console via multiple statements, I get the expected results:
0
1
But when I print the function out through just one cout statement on the same line, I get:
3 2
(This is after the initial 0 and 1 that were previously printed)
Why does it print backwards?
#include "stdafx.h"
#include <iostream>
using namespace std;
int addOne()
{
static int s_num = -1;
return ++s_num;
}
int main()
{
cout << addOne() << "\n";
cout << addOne() << "\n";
cout << addOne() << " " << addOne() << "\n";
return 0;
}
You are actually stumbling on unspecified behavior. In this context, and any other such context where the operators are of the same precedence, the function calls can be evaluated in any order. In this case, the compiler chose to evaluate the second function call before the first, but other compilers might do it differently.
Many warning messages (via std::cout) might be printed out during the process. Is there a way to postpone the printing of the warning messaged in the end of the program? There are huge amount of the processing information will be printed. I'm planing to have all the warnings together in the end rather than scattered around.
More background:
code is already there.
there are about 50 warning messages within the code (in case if there is some sort of delay( ) function, I don't want to add 50 times, would be nice if there is an globally delaye/postpone function for stand output)
Thanks
One way to do it is to send everything to a stringstream, and then print at the end.
For example:
#include <iostream>
#include <sstream>
int main(){
int i = 5, j = 4;
std::stringstream ss;
std::cout << i * j << std::endl;
ss << "success" << std::endl;
std::cout << j + i * i + j << std::endl;
ss << "failure" << std::endl;
std::cout << ss.str() << std::endl;
return 0;
}
Output:
20
33
success
failure
If you're just trying to delay all printing of std::cout what you can do is redirect standard out to a string stream that acts as a buffer. It's pretty simple and avoids all of the dup, dup2, and piping stuff that one might be inclined to try.
#include <sstream>
// Make a buffer for all of your output
std::stringstream buffer;
// Copy std::cout since we're going to replace it temporarily
std::streambuf normal_cout = std::cout.rdbuf();
// Replace std::cout with your bufffer
std::cout.rdbuf(buffer.rdbuf());
// Now your program runs and does its thing writing to std::cout
std::cout << "Additional errors or details" << std::endl;
// Now restore std::cout
std::cout.rdbuf(normal_cout);
// Print the stuff you buffered
std::cout << buffer.str() << std::endl;
Also in the future, you should really use a buffer for errors from the start OR at a minimum write errors and logging to std::cerr so that your normal runtime print outs aren't cluttered with errors.
I need a C++ function that dumps some text data (multiple lines) to the console:
void DumpData() const
{
std::cout << "My Data 1" << std::endl;
std::cout << "My Data 2" << std::endl;
}
This should be the default behaviour, however, it must also be possible to pass some other stream object that would be used instead of std::cout, something like this:
void DumpData(std::ostream& Stream = std::cout) const
{
Stream << "My Data 1" << std::endl;
Stream << "My Data 2" << std::endl;
}
Now to my questions:
What is the correct type I should use for the paramter (std::ostream& in this example)?
What is the default value, can I use = std::cout directly?
Moreover (3.), after the call to this function, if I pass my own stream object, I need to iterate over all strings in this stream line by line. What would be the best way to achieve this?
Why don't you just try it yourself?
Here's you code in Coliru for std::cout and std::stringstream as an example (constness of DumpData removed obviously):
#include <iostream>
#include <sstream>
void DumpData(std::ostream& Stream = std::cout)
{
Stream << "My Data 1" << std::endl;
Stream << "My Data 2" << std::endl;
}
int main() {
DumpData();
std::stringstream ss;
DumpData(ss);
std::string l;
while(std::getline(ss, l)) {
std::cout << l << std::endl;
}
return 0;
}
Output is what you expected.
1 and 2 are correct. Your other option is to use std::ostringstream, but since std::cout is a std::ostream you would need to define another function with this signature.
To iterate the custom output, I would convert the stream to a string, then use some kind of string splitting to read each line.
Adding to #Jay 's answer, you could use a template parameter to be able to use a variety of streams such as std::stringstream or a std::iostream as long as the template parameter supports the << operator.
template <typename T> // = decltype(something)
void DumpData(T& Stream = std::cout) const
{
Stream << "My Data 1" << std::endl;
Stream << "My Data 2" << std::endl;
}
You can take it one step further by ensuring the type T provided overloads the operator <<.
Also in some cases, certain (possibly custom) streams may not be able to support std::endl so it might be safer to default to using \n which is always nicer since it avoid unnecessary flushes.
I have the following function:
std::vector<double>residuals;
std::cout << Print_res(std::cout);
std::ostream& Print_res(std::ostream& os) const {
os << "\tresidual" << std::endl;
for (unsigned int i = 0 ; i < 22 ; i++) {
os << "\t\t" << residuals[i] << std::endl;
}
os << std::flush;
return os;
};
It prints the residuals correctly, but at the end of the output tags an address as follows:
2275
2279.08
2224.0835
0x80c5604
how do I fix this?
EDIT: after reading everyone's comments I replaced the call to the function Print_res with a std::copy as
std::copy(residuals.begin(), residuals.end(), std::ostream_iterator<double>(std::cout,"\n"));
and that did not print the address, so I presume there is something wrong in the way I have written the function.
std::cout << Print_res(std::cout);
This is not legal at global scope so the code that you have posted is not valid. If this statement were executed from, say, a function then Print_res would be called and then the return value of Print_res would also be streamed to std::cout. This is most likely not what you meant. You probably want just this:
Print_res(std::cout);
Your statement performs the equivalent of:
std::cout << std::cout;
In C++03 (which you must be using), std::cout has an operator void* (from std::basic_ios<char>) the result of which is what is being printed.