Unable to remove the random numbers after the output - c++

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;
}

Related

call function with cout inside a cout statement

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++ ..

Why is cout outputting outputting backslashes and digits when I use it again?

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?

C++ Function return string?

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.

how to call a function saved in string

if i have:
void print_1();
void print_2();
void print_3();
and i have another function called valid(); which return an integer
i want to declare a string = "print_x());"
and i want to replace x by the value returned by valid();
for example if the value returned by valid(); is 3
=====> the string will be ("print_3();")
and then i want to call the function which saved in the string variable,
i want to make call like this:
print_3();
how can i do that
This is "not possible directly".
You can, however, simply do:
switch (code) {
case 1: call_1(); break;
case 2: call_2(); break;
}
etc...
C++ does not have any support for that kind of programming.
If you only have three functions then you can parse the string and write a switch statement to call the desired function. However, I suspect that you are looking for something like the eval() function that is found in scripting languages like Perl, Python, Ruby, Lua etc. C++ has no such thing.
As others have pointed, your exact requirement is not fulfilled by C++. But you can consider the following code as an alternative to switch statement.
#include <iostream>
using namespace std;
void print_0()
{
cout << "Print 0\n";
}
void print_1()
{
cout << "Print 1\n";
}
void print_2()
{
cout << "Print 2\n";
}
typedef void(*FunctionPointer)();
FunctionPointer functionPointers[] = {&print_0, &print_1, &print_2};
int main(int argc, char **argv)
{
int return_value = 0;
functionPointers[return_value]();
return_value = 1;
functionPointers[return_value]();
return_value = 2;
functionPointers[return_value]();
return 0;
}
The code uses an array of function pointers to call a specific function as intended by the return value.

Void vs Int Functions

What would be the different between void and int functions? When do i use which? Would void be used when just printing out a message or a variable value? like cout << value;
Or would it just be text?
And is int used when you actually do calculations within it?
void is used when you are not required to return anything from the function to the caller of the function.
for eg.
void no_return_fn()
{
cout<< "This function will not return anything" << endl;
return; // returns nothing or void
}
int is used when you have to return an integer value from the function to the caller of the function
for eg.
int return_sum_of_integers_fn(int a, int b)
{
cout<< "This function returns an integer" << endl;
return (a + b); // returns an integer
}
Do you want the function to return anything? If not, then it should be void. If you want it to return an int, then it should be int. If you want it to return something else, then it should have some other return type.
Some prefer using functions that return int to indicate some errors or special cases. Consider this code:
int print (int* ptr)
{
if (ptr == NULL)
{
return -1; // Error code.
}
std::cout << *ptr;
return 1; // Success code.
}
when you use void, it means you don't want anything returned from the function.
while an int return may be a result of calculation in the function, or indicate the status when it returning, such as an error number or something else that can tell you what has happened when the function executing.
Like you heard above, void doesn't return value, so you use it when you don't need to do this.
For example, you can use 'void' not only to print text, but mainly to modificate a parameters (change something you already have), so you don't need to return a value.
Let's say you want to find int c , which is sum two (integer) numbers, a and b (so a+b=c). You can write a function which adds these numbers and assign it's value to c
int c;
int sum (int a, int b)
{
return a+b;
}
c = sum(a,b);
While using void, you will just modificate c, so instead of writing c = function(arguments) , you will have function(c) which modifies c, for example:
int c;
void sum(int a, int b, int c)
{
c = a+b;
}
sum(a,b,c);
After the last line, the 'c' you have is equal the sum of 'a' and 'b' :-)
You return void to indicate that nothing is returned.
An int return may or may not indicate that calculations have been performed (e.g. could just be a return code).
Another difference is that void function do not require to have a return inside it:
This 2 snippets of code are valid and do not generate a compiler warning:
Snippet 1
void msg1()
{
cout<< "This is a message." << endl;
return; // returns nothing or void
}
Snippet 2
void msg2()
{
cout<< "This is a message." << endl;
}
Both have the same behavior and no warning is displayed.
If you declare a function non void and you do not return a value your compiler is likely to display a WARNING like " warning: no return statement in function returning non-void".
It's depends on modifier parameters sent to compiler if this error is displayed or not.
This code is likey to display a compiler warning since no return :
int test(){
printf("test");
}
Actually,It is necessary if you are compiling your code for a hosted system, such as PC, Linux, Mac, Android. Then main must return int. If you are compiling code for a freestanding system, such as embedded microcontrollers, or if you are making an OS, then the return type of main can be anything.
Though no error will occur if you use int or void but its not compliance according to standard C.