Changing C++ output without changing the main() function [closed] - c++

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"... :)

Related

What is the purpose of declaring a function as a pointer?

I was looking through the source code of a project called CrossWindow-Graphics today when I saw an interesting function declaration. The code seemed to be declared as a function pointer. Here is a similar example I wrote.
#include <iostream>
using namespace std;
void (*Test())
{
cout << "Test Called!" << endl;
}
int main()
{
Test();
return 0;
}
My question is why does C++ allow this. I'd imagine it has something to do with function pointers. I remember that typedef is really just creating a variable and the name of the variable becomes the new type so I suppose this is just the same as creating a "variable" but it points to code. Even if that is the right idea, What is the purpose of that?
All you've really done here is add an extra pair of () that doesn't do anything.
We could write the same functin as
void* Test() { ... }
It's a function that returns a void*.
So the function should have a return statements where it returns a void pointer. Some compilers will warn about this as seen here.

Using c++ and trying to "nest" some code

I'm currently trying to create a basic quiz game in C++.
The following code throws an error when I try to run it, it works if I don't use answer("answer") in the main class and instead substitute it with the actual code.
I wanted to "nest" (I don't know the technical term) some of the code so that I did not have to keep writing it out every time, as you can see i was hoping to write any question followed by answer("answer").
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "QUIZ C++ EDITION!\n";
cout << "Question 1:\n";
cout << "What is the colour you get when you mix red and yellow?\n\n";
question("Orange");
system("PAUSE");
}
void question(string answer) {
string input;
getline(cin, input);
if (input == answer) {
cout << "\nCorrectimundo!\n";
}
else
{
cout << "\nWrongimundo.\n";
}
return;
}
I have a feeling it's a case of wrong syntax but the IDE is not showing me where the error is unfortunately, it only happens when I run the program.
It looks like you are trying to make a function. Can I help?
– Clippy (1997-2007 RIP)
Two ways to do this. One is to forward declare question ahead of its first use.
void question(string answer);
int main()
{
...
question("Orange")
...
}
void question(string answer)
{ ... }
A forward declaration is a promise to the compiler that question will be fully defined somewhere else, maybe later in this file, maybe in another file, maybe in a library. But it must be defined somewhere or the program will compile, but it will not link.
And the other is to fully define question ahead of it's first use.
void question(string answer)
{ ... }
int main()
{
...
question("Orange")
...
}
I prefer the second approach because there is no possibility of falling into a trap like this:
void question(int answer);
int main()
{
...
question(42)
...
}
void question(string answer)
{ ... }
and getting a linker error from changing the forward declaration of question and forgetting to change the definition.
You need to provide a declaration of the function question before you can use it in main. Add
void question(string answer);
before the definition of main.
In C++ you must declare a function before you can use it (note, definition is also a declaration), but there is no mention of function question before line
question("Orange");
when it is actually trying to get called. Add a declaration:
void question(string answer);
int main()
{
// the rest of code ...
You forgot to declare your function , you can either declare it before main or just write the whole function before main.
You need to add before your main:
void question(string value);

How can I call this function in main

// pointer to functions
#include <iostream>
#include <vector>
using namespace std;
struct boo{
string u;
int p;
};
vector <boo> om(boo &bo){
cin >> bo.u;
cout << bo.u;
}
int main(){
string q;
vector <boo> b;
om(b);
}
Ok I need to understand how will I be able to write vector<boo> om(boo &bo) into my main(). I always get some type of error with it and I need help with it. I can't ever call the function into main because I just simply don't know how to call it into main. Well I know how to call om([I just need help with this part]) I have no idea what to fill this in with.
P.S
Sorry this is at the bottom Im a noob with stackoverflow.
Taking a shot in the dark here because this seems to be the most likely intent. If i'm wrong, hopefully it is still instructional.
#include <iostream>
#include <vector>
I removed the using namespace std that was here because it's dangerous. Don't believe me? Do a quick search. StackOverflow is littered with "WTF is going on?" questions that resolve down to "something in the std namespace had the same name as your variable."
struct boo
{
std::string u;
int p;
};
I've left Boo alone to keep it recognizable to the OP. However, descriptive names really help your code explain itself. No one here, excluding the OP, has any clue what a boo represents and how it should be used or what it's members represent and how they should be used. This limits the our ability to assist the OP with debugging support and advice.
On to function om. Again, terrible name. A function name should provide some hints as to what the function does.
Assumptions:
Om is intended to
read in input to get the data required to fill out a boo structure
place that boo structure into main's vector b
With that in mind,
No need to return anything except perhaps an error code if the user fails to enter correct input.
The only thing worth passing in is a reference to the vector. The reference allows the vector supplied by the caller to be modified.
If we knew what a boo was someone might be able to suggest better ways to do this and validate the user input.
void om(std::vector<boo> &bo)
{
boo temp; //start by making a temporary boo
std::cin >> temp.u; // read user input into the temporary boo
// removed the print out here
bo.push_back(temp); // copy the temporary boo into the vector
}
main is altered to remove unused string q and output the contents of vector b
int main()
{
std::vector<boo> b; // usual nagging about non-descriptive name
om(b);
for (boo testboo: b)
{ // print all boos in b
std::cout << testboo.u << std::endl;
}
}
And as one cut-n-paste-able block for trying it out and playing around:
#include <iostream>
#include <vector>
struct boo
{
std::string u;
int p;
};
void om(std::vector<boo> &bo)
{
boo temp; //start by making a temporary boo
std::cin >> temp.u; // read user input into the temporary boo
// removed the print out here
bo.push_back(temp); // copy the temporary boo into the vector
}
int main()
{
std::vector<boo> b; // usual nagging about non-descriptive name
om(b);
for (boo testboo: b)
{ // print all boos in b
std::cout << testboo.u << std::endl;
}
}

What is the point of MyType(myVar) declaration in C++?

In c++11 standard we can declare variable in an unusual way. We can declare myVar as int(myVar); instead of int myVar. What is the point of this?
#include <iostream>
using namespace std;
int main() {
int(myVar);
myVar = 1000;
cout << myVar << endl;
return 0;
}
UPD Actually there is a certain reason why I asked this. What looked innocent just stopped to compile when we tried to port some code from MSVC C++03 to GCC C++11.
Here is an example
#include <iostream>
using namespace std;
struct MyAssert
{
MyAssert(bool)
{
}
};
#define ASSERT(cond) MyAssert(cond)
void func(void* ptr)
{
ASSERT(ptr); // error: declaration of ‘MyAssert ptr’
// shadows a parameter #define ASSERT(cond) MyAssert(cond)
}
int main()
{
func(nullptr);
return 0;
}
Sure. I can even do this:
int (main)()
{
}
Parentheses serve to group things in C and C++. They often do not carry additional meaning beyond grouping. Function calls/declarations/definitions are a bit special, but if you need convincing that we should not be allowed to omit them there, just look at Ruby, where parentheses are optional in function calls.
There is not necessarily a point to it. But sometimes being able to slap on some theoretically unnecessary parentheses helps make code easier to read. Not in your particular example, and not in mine, of course.
#include <typeinfo>
#include <iostream>
int main(void)
{
int *first_var[2];
int (*second_var)[2];
std::cout << typeid(first_var).name() << std::endl;
std::cout << typeid(second_var).name() << std::endl;
return 0;
}
Running this on my machine gives :
A2_Pi
PA2_i
The parenthesis in the declaration mostly serve the same purpose they do everywhere, group things that should be together regardless of the default priority order of the language.
Of course parenthesis with only one element inside is equivalent to just typing that element except in cases where parenthesis are mandatory (e.g function calls).
C++ does not break backward compatibility if it can help it.
The C that it was developed from had this syntax. So C++ inherited it.
A side effect of this backward compatibility are the vexing parse problems. They have not proved sufficiently vexing to justify breaking backward compatibility.

Dont modify program, print some values as output - unusual (?) homework [closed]

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.