'C++ endl not printing new line when called from a method

New to C++ My understanding is endl will add a new line. So with the following piece of code:

#include <iostream>

using namespace std;

void printf(string message);

int main()
{

cout << "Hello" << endl;
cout << "World" << endl;

printf("Hello");
printf("World");

return 0;

}

void printf(string message) {
cout << message << endl;
}

I expect the output to be:

Hello

World

Hello

World

But, strangely, the output is:

Hello

World

HelloWorld

Looks like, when called from the user-defined method, endl is not adding new line..?? What is wrong with my understanding here. Please advise.



Solution 1:[1]

It's using the inbuilt printf method. Try to explicitly use std::string so that it'll call custom printf method.

printf(std::string("Hello"));
printf(std::string("World"));

Or you can put your method in a different namespace:

#include <iostream>

namespace test
{
    extern void printf(const std::string& message);
}

int main()
{
    std::cout << "Hello" << std::endl;
    std::cout << "World" << std::endl;

    test::printf("Hello");
    test::printf("World");

    return 0;

}

void test::printf(const std::string& message) {
    std::cout << message << std::endl;
}

Solution 2:[2]

try renaming the "printf" function to "print" it works fine-

#include <iostream>
using namespace std;
void print(string message);

int main()
{

cout << "Hello" << endl;
cout << "World" << endl;

print("Hello");
print("World");
cout <<endl;
return 0;

}

void print(std::string message) {
cout << message << endl;
}

Solution 3:[3]

You should pick function name other than printf(); like Print().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronen
Solution 2 Suman
Solution 3 Peter Csala