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

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

Related

why i am not able to print data with for loop in c/c++?

I updated my code still it is not working.
i am using simple c++.
#include<iostream>
using namespace std;
class A
{
public:
void put_data()
{
cout<<"hello\n";
}
};
int main()
{
A a[3];
//working
a[0].put_data();
a[1].put_data();
a[2].put_data();
//Not working
for (int k=0;k<3;k++)
{
cout<<a[k].put_data();
}
return 0;
}
whe i try to access object array with directly it works well, but when i try to access it with for loop not working.
This is unnecessary:
cout<<a[k].put_data();
when the put_data() method has the cout contained inside it. It's also invalid because put_data() is void and doesn't return anything that cout could work with.
You probably mean to do just:
a[k].put_data();
You shouldn't even be able to compile this program. The expression cout << a[k].put_data() should give you a compilation error because put_data has void as its return type. Surely your compiler showed you that error message somewhere; make sure you know how to read compiler errors.

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.

How do I print a variable from main with a function in a class, Help understanding OOP c++

Section 9(1/4) out of 11 of my c++ introduction webclass;
I have no idea what I'm doing.
I'm unsure even of what terms to search for(first touch with OOP).
-
I need to print the cin in main with a function in a class,
So far I have come up with a class with a string variable and a function that do nothing;
#include <iostream>
#include <string>
using namespace std;
class printclass
{
public:
string array;
void print();
};
void printclass::print()
{
cout << array;
}
Main program(cannot be edited);
int main()
{
char array[50];
cout << "Enter string:";
cin.get(array, 50);
printclass printer;
printer.print(array);
}
It is my understanding that the printclass printer; creates an object 'printer' with the printclass class and thus knows how to use the functions in the class
on sort-of a blank page that is declared with the call, am I far off?
How do I print the value of the array in main with the function?
The exercise has been translated from finnish, please excuse blunt grammar and user stupidity.
Thank you for your time!
am I far off?
Kinda. You've incorrectly assumed the interface of your printclass. Here's a correct one1 from the example posted:
class printclass {
public:
printclass();
void print(const char* str);
};
From that it's quite easy to spot your mistake; you've assumed that your class has to store the array to print, while the interface passes it directly. It's enough to implement the print in terms of str without any member variables:
void printclass::print(const char* str) { // could be const
std::cout << str;
}
Note: the constructor can of course be left alone and it will default to what you want.
1One of many possible interfaces, but I've picked the most likely.

Simple c++ constructor don't work (very basic)

Ok, so I've decided to read a little c++ now and then, just to get a basic understanding of the syntax. I am familiar with Java, and a little bit of Python. I have 'read' through a c++ for dummies book, and I thought I had the grip - until I tried to create the simplest class.
The idea was very simple: a class (named ape) takes one parameter, an int, which is stored as a private field. It has one other function, a return function, which returns the field. The main() creates an instance, and calls the method to print out the variable.
The idea was to use a string instead of an int, but I couldn't get it working, so I decided to use an int instead, which, obviously, wasn't working either.
If it is to any interest I use Code::blocks, Windows 7 and the g++ compiler.
Here are the classes:
Main.cpp
#include <iostream>
#include "ape.h"
using namespace std;
int main()
{
ape asd(10);
cout << asd.getNumber();
}
ape.h
#ifndef APE_H
#define APE_H
class ape
{
public:
ape(int num);
virtual ~ape();
int getNumber();
protected:
private:
int number;
};
#endif // APE_H
and ape.cpp
#include "ape.h"
using namespace std;
ape::ape(int num)
{
tall = num;
}
ape::~ape()
{
//dtor
}
int getNumber()
{
return number;
}
The error messages I get seems very random to me, as they are changing completely with every single change I make, and are not very self explaining. I can see how I sound like an arrogant fool, and that this whole mess is the compilers fault, but I really don't see any connection between the error messages and what's wrong in my code.
Take it easy on me, first time here. :)
I guess I should probably add the error message:
undefined reference to 'ape::ape(int)'
Not much to say without the actual error messages, but at least here is a problem:
int getNumber()
{
return number;
}
This should be int ape::getNumber(). Also in your code there is no definition for tall, should perhaps be number instead?
You are assigning a value to a variable that doesn't exist.
Change:
ape::ape(int num)
{
tall = num;
}
To:
ape::ape(int num) :
number(num)
{
}
Moreover, I don't know why you wrote a destructor, and why you decided to make it virtual. By default, the compiler will generate an empty destructor (similar to yours, but not virtual). If you don't intend to do polymorphism (with inheritance and all that "stuff"), you may delete this destructor from your code as it only brings complexity for no gain.
You also need to prefix your method definitions with the name of the class:
int ape::getNumber() // Note the "ape::" here
{
return number;
}
One last thing:
You problably want to change also your main:
int main()
{
ape asd(10);
cout << asd.getNumber() << endl;
}
Something put into cout only gets printed when one outputs endl or flush as the stream is buffered.
Regarding your last edit:
I guess I should probably add the error message: undefined reference
to 'ape::ape(int)'
You probably failed to link with ape.o. In your compilation folder, you should have your source files and a .o for every .cpp. You have to link those object files together to build your program. This message indicates that the linker is unable to find the definition for ape::ape(int). That is he was probably not given the ape.o file.
Long story short, here is what your compilation commands should look like (using g++):
g++ -o main.o -c main.cpp
g++ -o ape.o -c ape.cpp
g++ -o program main.o ape.o
You are using undeclared field "tall". Seems like your constructor should be:
ape::ape(int num)
{
number = num;
}
ape::ape(int num)
{
tall = num;
}
tall? Where did tall come from? The member was declared as number.
Better would be
ape::ape(int num) { number = num; }
Much better would be
ape::ape(int num) : number(num) { }
You need to set variable number in constructor, before you can read it in getNumber.
Try this:
ape::ape(int num)
{
number = num;
}
What is tall? The private field is called number in your example, so this function:
ape::ape(int num)
{
tall = num;
}
should be:
ape::ape(int num)
{
number = num;
}
However, in C++ you should use initialization and not assignments. While for an int is not a big deal, for more complex objects assignment is more expensive as you are copying the object, while with initialization you can use the copy constructor. Therefore the convention is to initialize all variables before the body of the constructor.
ape::ape(int num)
: number(num)
{
}
And, please declare getNumber() as a const method. Here you have a nice guide explaining all the const variants: http://developer.kde.org/~wheeler/cpp-pitfalls.html
While you are at it, add the missing class prefix, which you need if you are defining the method outside of the declaration of the class:
int ape::getNumber() const
{
return number;
}
As a last comment, I recommend you look for a convention on naming member variables. Typical are mNumber or _number. Makes reading your own code easier later on.

Changing C++ output without changing the main() function [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.
#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"... :)