so I'm kinda new to c++ (actually very new) and I was messing around with my code:
#include <iostream>
using namespace std;
string aString()
{
cout << "Car" << endl;
}
int main()
{
cout << "Word:" << aString() << endl;
return 0;
}
I tried to get something like: "Word: Car".
It ended up not working and showing a bunch of weird characters. My question is can a function return a string like an integer does?
Sorry if this is a stupid question.
My question is can a function return a string like an integer does?
Sure, you want to write
string aString()
{
return "Car";
// ^^^^^^
}
If the function declares a return type, you actually need to return something, otherwise you have undefined behavior.
The compiler should have issued a warning about that.
std::cout is used to print out values at the terminal, not to return them from functions.
Related
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++ ..
I understand that void returns no values.
So how does it work in conjuncture to a function?
My understanding is that the purpose of a function is to return a piece of information after doing something with it.
so why would I want to return no value, and how would this be beneficiary?
My understanding is that the purpose of a function is to return a
piece of information after doing something with it.
In some (most of the) programming languages, functions have side effects also. Purpose of some functions is limited only to side effects and return value is not necessary. Such functions have void return type.
Some examples of side effects may be:
Update a global
File operation, logging etc where user doesn't want to know the status of operation
Freeing resources
C++ Programming Language Stroustrup 4th Edition book
When declaring a function, you must specify the type of the value returned. Logically, you would expect to be able to indicate that a function didn’t return a value by omitting the return type. However, that would make a mess of the grammar (§iso.A). Consequently, void is used as a ‘‘pseudo return type’’ to indicate that a function doesn’t return a value.
Edit:
When you don't expect something in return to the calling function, we use void function.
If void() does not return a value, why do we use it?
It can be pretty useful for modularizing output.
I'll provide you with an example:
#include <iostream>
#include <string>
using namespace std;
void displayMessage(string fName, string mName, string lName, string id);
int main() {
string student[4] = { "Mike", "L.", "Jason", "c23459i" };
displayMessage(student[0], student[1], student[2], student[3]);
return 0;
}
void displayMessage(string fName, string mName, string lName, string id)
{
double PI = 3.14159265359;
cout << "Student " << " information:"
<< "\nFirst name: " << fName
<< "\nMiddle Initial: " << mName
<< "\nFirst name: " << lName
<< "\nID: " << id
<< "\nThe Circumference of a circle with the radius of 2: " << (2*PI*2);
}
You can use void functions IF you don't need to return a value. If you plan to do calculations and return a value such as an int, use a function declaration with the return type of int.
I have this piece of code (something I threw together trying to isolate a weird error in a chess program I'm trying to write):
#include <vector>
#include <iostream>
class piece{
public:
piece() : COLOUR('C'){}
const char COLOUR;
};
std::vector<piece*> makeEmptyLine(){
std::vector<piece*> emptyLine;
piece null;
emptyLine.push_back(&null);
return emptyLine;
}
int main(){
std::vector<piece*> emptyLine = makeEmptyLine();
std::cout << (*emptyLine[0]).COLOUR;
std::cout << (*emptyLine[0]).COLOUR;
std::cout << (*emptyLine[0]).COLOUR;
return 0;
}
And the output is C\367\367
The first std::cout << (*emptyLine[0]).COLOUR; always prints "C" (the expected result). But when it's used again, it outputs that backslash and three digits which change depending on how many times I use cout in the program.
You have an undefined behaviour because you use the address of a local variable null which is destroyed once your function makeEmptyLine() returns.
Does your compiler complain when you try to compile it with the highest warning level?
I want to output the values of the private class members Bankcode and AgentName. How can I do this from within my main() function, or in general, outside of the BOURNE class.
My initial code attempts are below:
#include <iostream>
#include <string>
using namespace std;
class BOURNE
{
string Bankcode ={"THE SECRET CODE IS 00071712014"} ; /*private by default*/
string AgentName={"Jason Bourne"}; /*private by default*/
public:
void tryToGetSecretCodeandName(string theName ,string theCode); //trying to get the private
void trytoGetAgentName( string name); // try to get name
};
//***********************defining member function**************************************
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode) //member defining function
{
Bankcode=theCode; //equalling name to the code here
AgentName=theName; //the samething here
cout<<theCode<<"\n"<<theName; //printing out the values
}
//************************main function*****************************
int main()
{
BOURNE justAnyObject; //making an object to the class
justAnyObject.tryToGetSecretCodeandName();
return 0;
}
Third Answer
Your code has two 'getter' style functions, but neither one takes no arguments. That is, both of your functions require arguments to be passed.
Your main function is calling get...CodeandName(), which has no arguments. As such, you get a compiler error, probably complaining about valid signatures, or arguments passed.
Edited Answer
If you only want to get the values, the typical (as far as I am aware) implementation is something like
std::string BOURNE::getCode()
{
return Bankcode;
}
std::string BOURNE::getName()
{
return AgentName;
}
int main()
{
BOURNE myAgent;
cout<< "The agent's name is : " << myAgent.getName() << endl;
cout<< "The agent's code is : " << myAgent.getCode() << endl;
}
Original Answer, left in because I feel like it's more useful
I suspect what you're asking is if you could do something like
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode)
{
if (Bankcode == theCode) {
cout<< "You correctly guessed the code : " << Bankcode << endl;
}
if (AgentName == theName) {
cout << "You correctly guessed the agent's name : " << AgentName << endl;
}
}
This will allow you to repeatedly guess at the name, and get output when you're correct.
If you wanted to disable this kind of guessing, then you could consider creating a new class (possibly derived from/based on std::string - but see this question for reasons to be careful!) and implement an operator== function which always returned false.
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;
}