It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a problem with, to me, unusual homework:
Dont modify the main function but change the program that it prints as
output:
Monday
is the first day
of the week
And heres the given code:
int main()
{
cout << "is the first day\n";
}
Any help will be appreciated :)
What he's undoubtedly interested in your demonstrating is the fact that a global object (defined in the same translation unit) will be constructed before main is entered, and destroyed after main exits.
Be aware that when such a global object is being constructed, std::cout may not exist yet (and when it's being destroyed, std::cout may no longer exist), so any printing you do just about has to be via C functions like printf.
Another atrocious idea, just for the fun of it:
#include <iostream>
using namespace std;
#define main real_main
int main()
{
cout << "is the first day\n";
}
#undef main
int main()
{
cout << "Monday\n";
int res = real_main();
cout << "of the week\n";
return res;
}
Another version which does not rely on preprocessor foo would be to use global static object construction and destruction. This is safe, since apparently the standard guarantees that std::cout (and friends) is initialized and destroyed before/after all user code:
#include <iostream>
using namespace std;
struct Homework
{
Homework()
{
cout << "Monday\n";
}
~Homework()
{
cout << "of the week\n";
}
} hw;
int main()
{
cout << "is the first day\n";
}
Seems like a poor homework question. I can see no way to print other outputs without modifying the main method - unless you created another main method to override this?! The code provide is wrong as well - it should return 0 as main is expected to return an integer.
What about this?
#include <iostream>
#include <cstdlib>
using namespace std;
struct Foo
{
Foo()
{
cout << "Monday\nis the first day\nof the week\n";
exit(0);
}
} X;
int main()
{
cout << "is the first day\n";
}
Update
Ok, you may use name 'cout' in main func like some object not from iostream:
#include <iostream>
#include <string>
class Foo
{
public:
void operator <<( const std::string & s )
{
std::cout << "Monday\n" << s << "of the week";
}
} cout;
int main()
{
cout << "is the first day\n";
}
There are at least a couple of ways you can do this.
You can replace the meaning of cout.
You can make things happen before and after main is called.
Redefining cout:
#include <iostream>
class MyCout {};
void operator<<(MyCout& myCout, const char* message) {
std::cout << "Monday\n";
std::cout << message;
std::cout << "of the week\n";
}
MyCout cout;
int main()
{
cout << "is the first day\n";
}
To making things happen before and after main, you can create a static object. Their constructor is called before main, and the destructor afterwards:
#include <iostream>
class PrintExtras {
public:
PrintExtras() {
std::cout << "Monday\n";
}
~PrintExtras() {
std::cout << "of the week\n";
}
};
PrintExtras printExtras;
using std::cout;
int main()
{
cout << "is the first day\n";
}
I think you should make an operator overload for the output stream.
Think of things that happen before entry into main or after exit from main.
Early in a program you typically have initialization, at the end its counterpart.
What is the C++ idiom for those things?
How can you make those happen outside the body of main()?
What do you know about objects defined at namespace scope?
It really depends on where you are with your course, if you know about these things.
Alternative: The object used in main is only std::cout if you bring that name into the global namespace. Objects in namespaces other than ::std can also bear that name.
Related
In book "C++ Primer" fifth edition, there is a line "Entities with the same name defined in an outer scope are hidden" in the second page of Section 18.2.2. This sentence is underlined with red as follows:
I tried to repeat the claim in an experiment. The experimental code is as follows:
#include <cstdlib>
#include <iostream>
#include <cmath>
int abs(int n) {
std::cout << "here" << std::endl;
return 0;
}
void test() {
using std::abs;
std::cout << abs(7) << std::endl;
}
int main(int argc, char** argv) {
test();
return 0;
}
using std::abs is a using declaration, so, if the claim in "C++ Primer" is correct, the user-defined abs() function should be hidden by std::abs(). But the result is that it is the user-defined abs() function that is called. So, if the book is correct, there must be something wrong in my experiment. How do I write the experimental code to confirm the sentence in "C++ Primer"? If the book is incorrect, what should the correct exposition be that can replace the sentence? Thank you.
PS: I tried in both Windows10+VS2015 and Ubuntu 18.04+g++7.4. Both called user-defined abs() and printed out "here".
The book could do a better job of explaining it, but it isn't wrong. It's just that the lookup rules for overloads are somewhat more nuanced, because overloads of the same name may coexist in the same scope normally, so a using declaration mingles well with that.
If you were to indeed define a new entity that is not an overload, for instance
void test() {
int abs = 0;
std::cout << abs(7) << std::endl;
}
Then that call expression would be ill-formed, because the outer callable entities are hidden by the inner int variable. The way to work around it would be with a using declaration
void test() {
int abs = 0;
{
using std::abs; // Let the name refer to the functions again
using ::abs; // the variable abs is hidden
std::cout << abs(7) << std::endl;
}
}
This experiment should illustrate what the book meant.
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Can you please help me out with this issue?
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
char str[4];
A()
{
str = "C++";
cout << "Constructor A" << endl;
}
void display()
{
cout << str << " is your name" << endl;
}
};
int main()
{
A a;
a.display();
return 0;
}
It gives the following errors:
**************************Error**********
StringProg.cpp:9: error: ISO C++ forbids initialization of member "str"
StringProg.cpp:9: error: making "str" static StringProg.cpp:9: error: invalid in-class initialization of static data member of non-integral type "char [4]"
StringProg.cpp: In member function "void A::display()":
StringProg.cpp:17: error: "str" was not declared in this scope
**************************
There are quite a few issues with C arrays that prevent you from doing what you want to do.
String literals have type of const char[n] (n being their length + 1 for \0 character). To use them in C Standard Library functions, they decay to const char*, which don't carry the size of the string, and in order to find it, the strings need to be traversed (every character being looked at and compared to \0)
As a consequence, array assignment operator would need to be rather nontrivial; this isn't provided by the language, and you have to use library functions like strcpy to move the literal into your usable memory. In other words, you can't assign C arrays like other values.
Arrays function in a very primitive way; they don't have operators for comparison, it's harder to pass them to functions and store in the classes properly.
And so, because of all the above...
Prefer std::string to char[]:
class A {
std::string str;
public:
// prefer constructor init list
A() : str("C++") {
// your line would work, too
std::cout << "Constructor A" << std::endl;
}
void display() const {
std::cout << str << " is your name" << std::endl;
}
};
int main()
{
A a;
a.display();
// return 0; is unnecessary
}
Some "rules of thumb" (rules of thumbs?): if you need more than one element, start with vector<>. Never use C arrays. string is one element, not an "array of characters".
Try the following
#include<iostream>
#include<cstring>
class A
{
private:
char str[4];
public:
A() : str { "C++" }
{
std::cout << "Constructor A" << std::endl;
}
void display() const
{
std::cout << str << " is your name" << std::endl;
}
};
int main()
{
A a;
a.display();
return 0;
}
The program output is
Constructor A
C++ is your name
Take into account that arrays do not have the copy assignment operator. Thus this statement in your program
str = "C++';
even if to update the typo and write
str = "C++";
is invalid.
You could use standard C function strcpy declared in header <cstring>. For example
#include <cstring>
//...
A()
{
std::strcpy( str, "C++" );
std::cout << "Constructor A" << std::endl;
}
This question already has answers here:
Is it possible to detect namespace membership in C++?
(2 answers)
Closed 9 years ago.
I'm trying to write a log library which would use an external tool
To make the library more natural to use, i would like to be able to detect the namespace in which cout is used.
concretly the result should be used like this
namespace A
{
void foo()
{
cout << "Something went very wrong" << endl;
}
}
namespace B
{
void bar()
{
cout << "C should equal 3" << endl;
}
}
int main()
{
B::bar();
A::foo();
}
and the resulting output should look like this
MODULE::B : C should equal 3
MODULE::A : Something went very wrong
I already use std::streambuf to add certain keywords to the output of cout, all i need to be able to do is specify which streambuf to use in which namespace.
How do i achieve this?
Also the library i'm making is to be integrated in a project with multiple namespaces which making heavy uses of the using namespace declaration. I would need a solution which will not require to remove these declarations.
edit1: i don't care having to specify by hand which namespace is associated with which string or adding objects to any of the used namespaces (except std of course)
How about creating your custom logger stream? That way the user can specify the component that failed, like so:
namespace A {
void foo()
{
log("A") << "Something went very wrong" << endl;
}
}
namespace B {
void bar()
{
log("B") << "C should equal 3" << endl;
}
}
int main()
{
B::bar();
A::foo();
}
Perhaps less automagical, but __FILE__ macro could also give some information.
This is not possible in the language. If you are using Clang you could recompile Clang to perform such a task for you.
you may try to inject function like std::string namespace_name() in every namespace you want to show up, and then call std::cout << namespace_name() would lead most inner namespace name output
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
#include<iostream.h>
void main()
{
cout<<"Love";
}
The question is how can we change the output of this program into
"I Love You" without making any change in main().
Ok, fixing your main function and iostream.h ... This is the way
#include <iostream>
// to make sure std::cout is constructed when we use it
// before main was called - thxx to #chappar
std::ios_base::Init stream_initializer;
struct caller {
caller() { std::cout << "I "; }
~caller() { std::cout << " You"; }
} c;
// ohh well, for the br0ken main function
using std::cout;
int main()
{
cout<<"Love";
}
I figured i should explain why that works. The code defines a structure that has a constructor and a destructor. The constructor is run when you create an object of the struct and the destructor is run when that object is destroyed. Now, at the end of a struct definition, you can put declarators that will have the type caller.
So, what we did above is creating an object called c which is constructed (and the constructor called) at program start - even before main is run. And when the program terminates, the object is destroyed and the destructor is run. In between, main printed "Love".
That pattern actually is very well known by the term RAII which usually claims some resource in the constructor and releases it again in the destructor call.
#include <iostream>
class tclass
{
public:
void operator <<(char *s)
{
std::cout<<"I"<<s<<"You"<<std::endl;
}
};
tclass cout;
int main()
{
cout<<"love";
}
Not as elegant as litb's, but it works
#include <iostream>
#include <cstdio>
#include <sstream>
#define cout printf("I love you\n"); std::ostringstream os; os
int main()
{
cout << "love";
}
Of course, you don't need to use a stringstream, you could use any class with operator<<.
Not as elegant as litb's, but an alternative:
#include <iostream>
using namespace std;
int foo()
{
cout << "I Love You" << endl;
return cout.rdbuf(0);
}
int i = foo();
int main()
{
cout << "Love" << endl;
}
Like this:
#include <iostream>
int main() {
std::cout << "I Love You" << std::endl;
return 0;
}
/*
#include<iostream.h>
void main()
{
cout<<"Love";
}
*/
This way, you haven't changed anything in the main. :-p
We can do it like this too:
#include <iostream>
#include <cstdlib>
using namespace std;
int fnfoo(int inum){
cout << "I Love You" << endl;
return (exit(0),inum);
}
int dummy = fnfoo(5);
int main()
{
cout << "Love" << endl;
}
Simple and works perfectly ;)
That code has no using std but anyway it would require writing your own wrapper around cout and removing the using std if there was and replace with using mystd where the wrapper is defined.
I guess you could write an operator<< that added "I" before and "You" after the current output.
Shouldn't your main function return an int? You're either going to need to change the method, or write another program that this one pipes into, but that's the most round about way to change a simple string...
The lesson is that C++ can execute code before and after main() through static constructors/destructors, eg. the code posted by litb.
Assuming this was a class assignment, I would bet the idea was that you could rewrite iostream.h, since C++ doesn't treat it as special (for certain definitions of "special").
You need to change the main, by either calling another function or by changing the text. Since main() is the main output of your program
Can you be a little more precise?
You want the output of that piece of code to be "I love you" instead of "Love"?
Edit: I don't think you can't without changing at least one line of code in main(). You can either change from cout<<"Love" to cout<<"I love you" or just add a function that outputs that specific line.
I'm really surprised that noone suggested #define "Love" "I love you"... :)