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

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.

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.

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

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

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

Related

Calling a string getter function from a header file

I'm learning C++, and I'm just messing around with putting classes in separate files for practice. I have a getter function, which returns a string (because the variable is saved as a string). However, from my main() function, I am not sure how to call it. I know the problem is probably that I need to include string somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. I'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I've tried throwing in string in a couple of places when calling or creating the object, but I always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
main.cpp
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
Expected result: runs getUsername() function and returns usernameVar
Actual result: doesn't run the getUsername() function
The current code would not compile, because you have not specified return type of 'askUsername()' routine, which is 'void', I believe.
Other things are good, apart from an output in 'getUsername()', which happens after returning from the function and about which you should have received a warning, I guess.
To the question: you can call that 'get' method in 'main()' as:
cout << usernameobject.getUsername();
Your code should be structured more like this instead:
main.cpp
#include <iostream>
#include "usernameclass.h"
int main()
{
usernameclass usernameobject;
// optional:
// usernameobject.askUsername();
// do something with usernameobject.getUsername() as needed...
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
std::string getUsername() const;
void setUsername(std::string name);
void askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include <iostream>
#include "usernameclass.h"
std::string usernameclass::getUsername() const {
return usernameVar;
}
void usernameclass::setUsername(std::string name) {
usernameVar = name;
}
void usernameclass::askUsername() {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, std::name);
setUsername(name);
std::cout << "Ah, so your name is " << getUsername() << ", great name I guess!" << std::endl;
std::cout << "You're about to do some stuff, so get ready!" << std::endl;
}

Does the stream operator exist for class member functions?

I included the logger from boost. I'm pretty pleased how it works. Just for simplicity and the reason I don't want to use makros to often in my code, I wrap it in a class.
I now wonder if I could use the streaming operator << to write on a member function.
code
class LogWrapper{
...
//debug function
//info function
...
}
void main() {
LogWrapper log;
log.debug() << "some debug msg"; // does this exist?
log.info() << "some info msg";
}
output
[some_timestamp][debug] some debug msg
[some_timestamp][info] some info msg
Is this possible in a good practice, or is it entirely bad style?
It can be done easily like this:
#include <iostream>
class A {
public:
std::ostream &debug() const {
std::cerr << "[timestamp]" << "[DEBUG]";
return std::cerr;
}
};
int main()
{
A a;
a.debug() << "Test";
}
But the important question here is: Should we implement it in this way? In my opinion, NO!
Because you are thinking that the User of the class will print the logs like this:
int main()
{
A a;
a.debug() << "Test" << std::endl;
a.debug() << "Test2" << std::endl;
}
Output:
[timestamp][DEBUG]Test
[timestamp][DEBUG]Test2
But what if User chooses this way:
int main()
{
A a;
auto &out = a.debug();
out << "Test" << std::endl;
out << "Test2" << std::endl;
}
Output:
[timestamp][DEBUG]Test
Test2
I would highly recommend not to return stream object. You should use member functions for this purpose.
#include <iostream>
class A {
public:
static void debug(const std::string &log) {
std::cerr << "[timestamp]" << "[DEBUG]" << log << std::endl;
}
};
int main()
{
A::debug("Test 1");
A::debug("Test 2");
}
Output:
[timestamp][DEBUG]Test 1
[timestamp][DEBUG]Test 2

Passing null string to function as an argument

What is the right way of passing NULL string to a function without creating a variable?
I see compilation error with following code and I don't want to change the definition. Also may have to make change to string so don't want to mark it a constant type.
#include <iostream>
#include <string>
using namespace std;
void
myfunc(int i, string &my) {
if (my.empty()) {
cout << "Empty" << endl;
} else {
cout << "String is " << my <<endl;
}
}
int main ()
{
std::string str1 ("Test string");
myfunc(1, str1);
std::string str2 ("");
myfunc(2, "");
return 0;
}`
my1.cpp:18: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’
my1.cpp:6: error: in passing argument 2 of ‘void myfunc(int, std::string&)
’
Following compiles but I dont want to create local variable
#include <iostream>
#include <string>
using namespace std;
void
myfunc(int i, string &my) {
if (my.empty()) {
cout << "Empty" << endl;
} else {
cout << "String is " << my <<endl;
}
}
int main ()
{
std::string str1 ("Test string");
myfunc(1, str1);
std::string str2 ("");
myfunc(2, str2);
return 0;
}
The solution here is to have an overload that doesn't have the string parameter.
void myfunc(int i, string &my) {
cout << "String is " << my <<endl;
}
void myfunc(int i) {
cout << "Empty" << endl;
}
int main ()
{
std::string str1 ("Test string");
myfunc(1, str1);
myfunc(2);
}
This is the most simple and clear solution that conveys exactly your intent and functionality.
You shouldn't try to do it your way because if you want to modify the argument then the parameter should be "non-const reference" and so it cannot bind to temporaries. Thus you can't pass a string literal to it.
If you want to make it explicit that you don't pass a string, you could create a tag ala nullptr, although I do not recommend the extra complication when the above variant is clear and understood by everybody at first glance.
struct no_string_tag_t {};
constexpr no_string_tag_t no_string_tag;
void myfunc(int i, string &my) {
cout << "String is " << my <<endl;
}
void myfunc(int i, no_string_tag_t) {
cout << "Empty" << endl;
}
int main ()
{
std::string str1 ("Test string");
myfunc(1, str1);
myfunc(2, no_string_tag);
}
If you really want a single function, then the semantically correct version would have an optional reference.
auto foo(int i, std::optional<std::reference_wrapper<std::string>> my)
{
if (my)
cout << "String is " << my <<endl;
else
cout << "no string" << endl;
}
int main ()
{
std::string str1 ("Test string");
myfunc(1, str1);
myfunc(2, std::nullopt);
}
If you want to keep the function signature and still be able to pass it a temporary, then you are out of luck. C++ has a safety feature in that it does not allow a non-const lreferece to bind to a temporary. The reason for this restriction is that attempting to modify a temporary via a lreference would most likely be bug and not the programmers's intent since the temporary dies out anyway.
You can't pass a temporary to a non-const reference parameter. The object, being temporary, will be destroyed as soon as the function returns. Any changes that the function did to the object would be lost.
If you want to have the chance to modify the string, you can take the string by const reference and return a modified string.
string myfunc( int i, string const &s );
:
str1 = myfunc( 1, str1 );
auto result2 = myfunc( 2, "" );
Your other option is to use a pointer to a string that can be null.
void myfunc( int i, string *s ) {
if (!s) {
cout << "Empty" << endl;
} else {
cout << "String is " << *s <<endl;
}
}
myfunc( 1, &str1 );
myfunc( 2, nullptr );
You can ommit 1 or more arguments in functions calls as long those argument(s) are the last ones in the order or the args prototyped in that function.
You can also give a padron value if the argument is ommited when calling the function.
using namespace std;
void sTest(int a, string x ="TEST", int z=0);
void sTest(int a, string x, int z)
{
cout << x;
}
int main()
{
sTest(5); // displayed “TEST”
}

Programming error in C++

I recently started learning C++ but I came across a problem. The program given below is not giving me the desired result as I only see 'Hi' in the result but not what's written in the void function. Please tell me the reason that this is happening along with the solution.
I am using Xcode 6.3.1 and the I have selected the language C++.
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
void ABC ();
return 0;
}
You are redeclaring a void ABC() function inside main(). Just call ABC(); without the void.
You can take a look at this question about declaring a function within the scope of another.
In your code your function call was wrong.
When you call your function you don't need to add the return type:
#include
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC ();
return 0;
}
you need to call your method and not declare it inside main
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
EDIT 1:
Since you started learning C++ i recommend the following recommendations to make sure your code is cleaner. Please note , these are not rules by any mean , but more of best practices and a style of coding.
Use meaningful names for your variables, methods, functions , classes
... So instead of ABC() name it something that if you (or someone
else is reading it) will now what it suppose to do.
When calling methods and functions try to declare them with the
appropriate returning value. Void by definition doesn't return any
value it just process the code inside of it. so your methods/function
should return appropriate values of do what it suppose to.
Here's version 2 of your code with examples of 3 different methods and calls:
#include <iostream>
using namespace std;
int sum;
string MethodReturningString()
{
return "Hey there i am the result of a method call !";
}
int MethodReturningInt()
{
return 5;
}
void CalculateSum(int x,int y)
{
sum=x+y;
}
int main()
{
cout << MethodReturningString() << endl;
cout << MethodReturningInt() << endl;
cout << "Calculating sum:" ;
CalculateSum(5,4);
cout << sum << endl;
return 0;
}
Happy coding
In C++, like pretty much any other language, you do not specify the return type when calling a function. So change the line that reads:
void ABC ();
to:
ABC();
Try this:
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC();
return 0;
}
You should call a function simply by stating its name and adding parentheses.
instead of using void ABC() for calling the function ABC() in main(), use the following code:
#include
void ABC ()
{
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}

How to call a function inside a class

I am trying to call a function inside a class, when I try I get the error "no operator << matches these operands" right before instructor.displayMessage(). Also, am I calling instructor.displayMessage() correctly? I am new to c++
#include <iostream>
#include "GradeBook.h"
using namespace std;
int main()
{
GradeBook gradeBook1("CS101 Introduction to C++ Programming");
GradeBook gradeBook2("CS102 Data Structures in C++");
GradeBook instructor("");
instructor.setInstructorName();
cout << "gradeBook1 created for course: \n" << gradeBook1.getCourseName() << instructor.displayMessage()
<< "\ngradeBook2 created for course: \n" << gradeBook2.getCourseName()
<< endl;
cout << "\nPress any key to exit" << endl;
getchar();
}
Header:
#include <string>
using namespace std;
class GradeBook{
public:
GradeBook(string);
void setCourseName(string);
string getCourseName();
void displayMessage();
void setInstructorName();
string getInstructorName();
private:
string courseName;
string instructorName;
};
I didnt include the functions because I dont think they are part of the problem.
void displayMessage();
This function does not return anything, yet you try to print its return value here:
cout << "gradeBook1 created for course: \n" << gradeBook1.getCourseName() << instructor.displayMessage()
If it actually should return something, then you have to declare it with the correct return type, for example
string displayMessage();
However the name suggests that the function itself prints the output already. So maybe you simply want to call it, like this:
instructor.displayMessage();
in a single line.
If you provide the implementation of displayMessage() I might give a more precise answer.