Prasanjeet Mohanty
Prasanjeet Mohanty

Reputation: 31

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.

Upvotes: 1

Views: 884

Answers (4)

Harsh Panchal
Harsh Panchal

Reputation: 300

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

Upvotes: 0

user12002570
user12002570

Reputation: 1

The problem is that due to overload resolution the built in printf function is selected over your custom defined printf function. This is because the string literal "Hello" and "World" decays to const char* due to type decay and the built in printf function is a better match than your custom defined printf.

To solve this, replace the printf calls with :

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

In the above statements, we're explicitly using std::string's constructor to create std::string objects from the string literal "Hello" and "World" and then passing those std::string objects by value to your printf function.

Another alternative is to put your custom printf inside a custom namespace. Or you can name your function other than printf itself.

Upvotes: 3

Suman
Suman

Reputation: 364

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

Upvotes: 0

Ronen
Ronen

Reputation: 311

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

Upvotes: 2

Related Questions