call function with cout inside a cout statement - c++

Firstly please have a look at some simple codes that my questions derived from.
#include <iostream>
#include <string>
using namespace std;
string get_something()
{
cout << "output something";
return " and return something";
}
void print_something()
{
cout << "print something";
}
int main()
{
cout << get_something(); // will work
cout << print_something(); // will NOT work
return 0;
}
The only different thing I notice between get_something() and print_something() is that one is a return type and one isn't. As you can see I have added comments indicating that which one will work and not work.
However, I am really not sure what is happening behind the scene that makes it one possible and the other not possible.
I am not even sure how I should go about and search for this kind of question too.. so here I am asking a question.
Please enlighten me..
edit:
I am confused that how it is possible to do cout after cout..
both of the functions do that but one of them works and the other doesn't.

This seems to be a very common misunderstanding among beginners. Printing something via cout is not the same as returning a value from a function. Thats completely orthogonal things.
You can write:
std::string returned_value = get_something();
std::cout << returned_value;
But you cannot write:
??? returned_value = print_something();
std::cout << returned_value;
because print_something() does not return anything! void denotes the absence of a type. You cannot have an object of type void.
On the other hand, when you call a function, you can use the returned value (above), or you can ignore it, so this is correct code:
print_something(); // prints something
get_something(); // also print something and returned value is ignored
Note that the function get_something should get a better name, because it is not just "getting" a value. How about print_and_return_something()?
PS:
What I am really confused about is that, how is it possible to do a cout after a cout? Am I just missing what cout actually does?
Not sure If I understand, but I will try... std::cout is an object of type std::ostream. It has an operator<< that you can call, similar to calling methods of other objects. The following two are identical and just use different syntax:
std::cout.operator<<( "Hello World");
std::cout << "Hello World";
When you call print_something() then first the function is executed, then the return value is returned to the caller and execution continues with the caller. This:
std::cout << get_something();
is more or less the same as (well, its a crude simplification, but should be ok here):
// inside get_something
std::cout << "output something";
// return value
std::string result{"output something"};
// now execution continues in caller
std::cout << result;
Calling cout after cout is no different from calling some other function. Suppose you have a function print() that prints something then you can write
std::string print_and_return() {
std::string x{"Hello World"};
print(x);
return x;
}
The caller can do
std::string x = print_and_return(); // <- this already calls print()
print(x); // now we call it again
This is more or less the same as yours, just that I used some hypothetical print() instead of std::cout::operator<<.

Both your functions have a return type. It's just that one of them has a void return type.
The std::ostream class does not have an overload for << that takes a void type. This is sensible - what would be written to the stream in that case?
(cout is an instance of std::ostream that typically writes itself to the standard output which is normally the shell you're using to launch the program.)

Because print_something() has nothing to return, and cout want something to write to the console (the return value it is expecting). Therefore, it will give error.
get_something(), on the other hand, has something to return. So after executing it's rest of line (except return statement) it return the string, which gets printed by cout

get_something() returns something (what seems to be accepted by cout), so cout will receive the returned thing and will work.
On the other hand, print_something() returns nothing (because its return type is void), so cout cannot receive anything to print and won't work.

cout is a stream object.and we use << (insertion operator) to insert value like String,float,Int etc to it which will be displayed in output Screen.Since print_something() is not returning any value so nothing is inserted in stream ,That's why it is not working.
I recommend you to read about Streams in c++ ..

Related

Can't clear string reference

I have the following program in which the private string mOutStr is filled with characters in method "FetchSessionStatus".
After that, if mOutStr is empty (aka: FetchSessionStatus doesn't fill it or some other error happened) mOutStr is replaced by a "default string" called mAliveMsg.
Finally mOutStr is passed by reference to method OnCommand. OnCommand writes the string inside a pipe and then should clear mOutStr. However, the clean never works: mOutStr remains filled.
void RtnodeSpvSession::EnqueueRead()
{
std::string sCmd;
FetchSessionStatus();
(mOutStr.empty()) ? sCmd = mAliveMsg : sCmd = boost::ref(mOutStr);
OnCommand(sCmd);
}
void RtnodeSpvSession::OnCommand(std::string& sCmd)
{
std::cout << "Sending message " << sCmd.c_str() << " of "<< sCmd.size() << " size\n";
write(fd[1], sCmd.c_str(), sCmd.size());
sCmd.clear();
}
//Simplified version of FetchSessionStatus
void RtnodeSpvSession::FetchSessionStatus()
{
mOutStr+="x";
}
The end result is that, cycle by cycle, mOutStr keeps increasing in size, which means sCmd.clear is not working (aka the pass by reference is not working) but I don't understand what I'm supposed to do.
Well the issue here is that you're not passing the string you think by reference.
In your case, boost::ref return a reference wrapper to mOutStr, however, when you assign it to sCmd, it'll copy the content of mOutStr into sCmd.
In your OnCommand function, sCmd is a reference to sCmd in RtnodeSpvSession::EnqueueRead, not to mOutCmd. If you want to clear mOutCmd, you have to either do it in EnqueueRead, or to actually pass it to the OnCommand function.
For clarification, reference_wrapper<T> offer an implicit conversion to T&, but std::string::operator=(const &str) does a copy of str into the left operand, and do not replace said operand.

Why does passing local variable by value work?

# include <iostream>
# include <string>
using std::string;
using std::cout;
using std::endl;
string func() {
string abc = "some string";
return abc;
}
void func1(string s) {
cout << "I got this: " << s << endl;
}
int main() {
func1(func());
}
This gives:
$ ./a.out
I got this: some string
How/why does this code work ? I wonder because abc went out of scope and got destroyed as soon as the call to func() completed. So a copy of abc cannot be/should not be available in variable s in function func1 Is this understanding correct ?
The return value is copied from the local variable, effectively creating a new string object.
However, RVO (returned value optimization) should eliminate this step.
Try single stepping your code in a debugger. You should see the std::string copy constructor called for the return line. Be sure to compile with debug enabled and optimizers off.
Your code is essentially asking:
"Call func1, and in order for func1 to work I have to receive a string which we can use by calling the copy constructor on that string. The parameter for func1 we want to come from the return value of func (which we know has to be a string since its explicitly defined".
abc goes out of scope only after the copy constructor is called on the return value of func() which passes the value of the string. In theory you could have written it passed by reference or constant reference:
void func1(string& s) {
cout << "I got this: " << s << endl;
}
Which allows func1 to directly access the string in memory through a pointer (and also change it, if your code was meant to.)
void func1(string const& s) {
cout << "I got this: " << s << endl;
}
Which provides a constant reference to the string from func(). This ensures that you get a pointer to the data and that you won't change its contents. Typically passing data by constant reference (const&) is desirable because it's very fast and keeps your code from accidentally changing data that it shouldn't.
You really only need to pass by value if you're going to manipulate the data once you pass it to the new function, saving you the resources of creating another new container to handle the manipulation:
void func1(string s) {
s += " some extra stuff to add to the end of the string"; //append some new data
cout << "I got this: " << s << endl;
}

How do I output the cout output from a method into an ofstream file in c++?

I have a main function that prints a sudoku game to the console as I play. I call a print board method which outputs the board along with a 2D array with the numbers. I've been modifying the game to output to the file after every cout:
cout << "puzzle created" << endl;
output << "puzzle created" << endl;
Then the problem is that there is an error when I try the same with a method:
sudoku.printBoard(); //method to print board to console
I can't simply say:
output << sudoku.printBoard();
and I can't say:
output << "number";
in the method in the board.cpp file either.
Does anyone know any way around this?
This is the problem with print() member functions, and the reason you shouldn't write them. At least, not like this. You've locked yourself into printing to stdout, and now that you want to print somewhere else instead, you're stuck.
Instead, have a function that prints where you tell it to. This may be stdout or a file or whatever.
The function will be declared like this:
void printBoard(std::ostream& os);
and inside its definition, you will use os rather than std::cout.
Then your code will look like this:
sudoku.printBoard(std::cout);
sudoku.printBoard(output);
It works because both std::cout and output are of types that derive from std::ostream.
If you need the cout variant a lot, and you don't want to provide the argument every time because it's getting messy, simply provide an overload:
void printBoard()
{
printBoard(std::cout);
}
Now you can still write:
sudoku.printBoard();
Whether this is more or less confusing for developers on your project is for you to decide.
If you don't have other things to print, so that this is the only function of its kind within the type of sudoku, a more idiomatic approach would be to create an operator<< for that type:
std::ostream& operator<<(std::ostream& os, const SudokuBoard& board)
{
board.printBoard(os);
return os;
}
Now you can use it like this:
std::cout << sudoku;
output << sudoku;
Make a class that takes two ostreams in the constructor. One of these can be std::cout. Store these in the class as references.
Create output stream operators (<<) and use those to write to the two streams.
To use this in other classes pass it as a reference in their constructor (look up dependency injection).
Pass ofstream as a reference to your funtion or simply return string from your function and print it in main() or callee function.
In 2nd case you go like this
string f()
{
ostringstream os;
os<<"whatever I want to print in output";
....
...
return os.str();
}
int main() or //womain() from wherever you call
{
output<<f()<<endl;
}

c++ using function of type void or std::ostream & to do prints?

I am wondering what the reasons and advantages of defining a function with an std::ostream & return type are as opposed to just a void function for printing values. For instance if I wanted to print a string literal I could do it in the following two ways:
std::ostream& print1(std::ostream &os){
os << "print this message";
return os;
}
print1(std::cout);
or
void print2(){
std::cout << "print this message";
}
print2();
Now what would be the advantage of using a function like print1 as opposed to print2? Is one more efficient than the other, and are there other important differences?
The advantage of the first form is that you can for example combine several output functions:
print1(mystream)<<" and that's all !";
More practically, you could easily use file output instead of console output, or even string output. You can also write loops/conditions checking if everything went right, like you would do with standard output functions. Yes, because when you write to a file, things can go wrong (e.g. disk full):
if (! print1(mystream))
cout <<" dik full !?";
But it's just a common practice. You could of course as well choose the second form:
print2(); // yes, put on what stream, always cout ??
if (! cout)
cout <<" oops, unexpected output error...";

Unable to remove the random numbers after the output

I want to build a program that support multi-language but if I included the language selection code into the main function it will be messy, so I make another function called language then I wrote the code below:
#include <iostream>
int language() {
std::cout << "1.English\n2.中文";
}
int main() {
std::cout << language();
}
Then my Code::Blocks IDE gave me a warning:
*warning: no return statement in function returning non-void [-Wreturn-type]|*
I still can compile the code using MinGW via command prompt, but the compiled program gave me the output below:
1.English
2.中文4683872
Then I add return 0; after the std::cout << "1.English\n2.中文"; but it display 0 instead of 4683872 above.
I am still learning C++ and I have no idea what happened to my code, and is there is any ways to remove those numbers?
In your program, you print your string first and after you print the return value of the function... That's why you have a number after the string.
Just try :
// I don't think your language function need to return something
// So make it void
void language() {
std::cout << "1.English\n2.中文";
}
int main() {
language(); // Here no need to print the value returned by the language function
return 0; // Main return an int, 0 is for success
}
Just to explain a bit more :
The fact that your language() function return an int value and that you are not returning anything leads to Undefined behaviour. That's why you get a value like 4683872. And it is also why you have a warning at the compilation.
You have two problems in your code: The first is that you declare language as returning an int but then not actually returning anything. This is what the warning is about. The other problem is based on the first one, and that you actually use this "returned value" even though there is none, which leads to undefined behavior.
You can solve it in two ways: Either return a valid value from the function, or declare it as returning void and don't use the function in an expression.
You've got to get your return values sorted out! You want the language function to return an output stream, since you're feeding it's output into std::out in main. You might as well pass in an output stream into language so you could reuse it with a different output stream to std::out. Also, main has to return an int. Standard practice is to return 0 unless there's an error.
#include <iostream>
std::ostream& language(std::ostream& os) {
os << "1.English\n2.中文";
return os;
}
int main() {
std::cout << language(std::cout) << std::endl;
return 0;
}
If you want the user to select a language then your code needs to be more like this:
#include <iostream>
int language() {
int choice;
std::cout << "1.English\n2.中文"; // print menu of language choices
std::cin >> choice; // get selection from user
// NB: real code would have error checking here to make sure that `choice` is valid
return choice; // return selection
}
int main() {
std::cout << language();
}
The std::cout << language(); is printing an integer for you since language() returns an int. If you don't want anything to print after your text, then remove the std::cout << in your main.
#include <iostream>
void language() {
std::cout << "1.English\n2.中文";
}
int main() {
language();
return 0;
}