// 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;
}
}
Related
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.
in first, want to start to mention that it could be sorry for my bad english.
in C++, when we want to create a instance of certain type of class, we usually use "ClassType ObjectName;"
for example,
class Foo {};
Foo instance1;
but, i've met some codes make me embarassment a little. it following next.
class A {/*....bla bla*/};
class B {
public:
B(char*) {}
};
void main() {
A aaa;
B(aaa); // this makes a error.
}
by trial and error, i could know that "B(aaa);" is exactly same to "B aaa;".
But why? is this a kind of what depicted on standard documents? if so, please let me know where i can see.
Thanks in advance.
UPDATE:
Thank you for your all replies.
But i think that i've omitted some codes. Sorry.
#include <iostream>
using namespace std;
class A
{
};
class B
{
public:
B() { cout << "null\n"; }
B(char* str) {}
void print() {
cout << "print!\n";
}
};
void main()
{
A aaa;
//B(aaa); this line makes a error that says 'redefinition; different basic types'. VS2008
B(aa1);
aa1.print();
}
Output:
null
print!
as you can see, "B(aa1)" statement means not to pass aa1 to constructor as argument, but to create a instance aa1.
Until now, I've known "B(argument)" to "Pass argument to propel one of a overloaded construtor, and create a nameless temporary instance".
but value "aa1" looks lke neither a defined value nor a temporary instance.
Sometimes a set of parenthesis is needed to disambiguate declarations.
For example:
int *f(); // a function returning a pointer to int
int (*f)(); // a pointer to a function returning an int
Rather than listing exactly when and where using parenthesis is required and where it perhaps should be forbidden (because it is useless), the standard just says that they are allowed.
So you end up with the slightly confusing:
int a; // an int variable
int (b); // another int variable
Ok so I'm confused about all this operator overloading stuff, the syntax is just weird to me and I'm not that great at programming anyway. So looking around on the internet apparently I think the only way for me to print out objects using cout << is to overload it. So I have a vector of objects and normally if I just had a regular vector of ints or strings then I'd just use an iterator and go through each one and then dereference it to print out whats in it, but I don't think that technique is working for the objects :-/ Here is what I have so far...help!
BarOne.h //my header file
#include <string>
#include <vector>
using namespace std;
class BarOne
{
private:
string name;
string type;
string size;
vector<BarOne> bar; //vector of BarOne objects
vector<BarOne>::iterator it; //iterator for bar
public:
BarOne(); //constructor
void addBottle(string, string, string); //adds a new bottle to bar
void revealSpace();
void printInventory();
friend ostream& operator<<(ostream& os, const BarOne& b);
};
and my implementation looks like:
BarOne.cpp //implementation
#include "BarOne.h"
#include <iostream>
#include <string>
using namespace std;
BarOne::BarOne()
{
//adding 4 default bottles
}
void BarOne::addBottle(string bottleName, string bottleType, string bottleSize)
{
name = bottleName;
type = bottleType;
size = bottleSize;
}
void BarOne::printInventory()
{
for (it = bar.begin(); it != bar.end(); ++it)
{
cout << *it << endl;
}
}
ostream& operator<<(ostream& os, const BarOne& b)
{
os << b.name << "\t\t\t" << b.type << "\t\t\t" << b.size;
return os;
}
so how come when i call printInventory in my main it doesn't do anything? Did I do the overloading wrong? Syntax mistakes?
ok this is the main too:
#include "BarOne.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Tiqo, Peruvian, Wellington, Smooze;
string vodka;
string rum;
string whiskey;
string small;
string medium;
string large;
//default bottles
vector<BarOne> bar; //vector of BarOne objects
vector<BarOne>::iterator it; //iterator for bar
BarOne Inventory; //BarOne object
Inventory.addBottle(Tiqo, vodka, large);
bar.push_back(Inventory);
Inventory.addBottle(Peruvian, rum, medium);
bar.push_back(Inventory);
Inventory.addBottle(Wellington, vodka, large);
bar.push_back(Inventory);
Inventory.addBottle(Smooze, whiskey, small);
bar.push_back(Inventory);
^^^thats just a piece of it...the rest is just formatting how things are displayed when the program runs and stuff. So ok I'll try and separate the classes like someone suggested tho. AddBottle adds the info for that object in the vector right? it gets the info and then adds it into the variables name, type and size and then its put into the vector "bar". Or no?
You don't show us your main() program. That code, together with your class design which confuses bar contents with the bar is causing the behavior you see.
The operator << is actually OK for outputting data of a bottle. But I'm sure that the BarOne on which it is called has an empty bar vector. Your addBottle() doesn't add anything anywhere (in particular not to the contained bar). Instead it simply sets the properties (data members) of the outer BarOne object.
The origin of that confusion is your class design, where a BarOne apparently is intended to serve both as bottle and as bar (which contains bottles).
I suggest you restart and try with separate Barand Bottleclasses.
BTW: Keeping the iterator you use in local loops as a class member is not a good idea. Sooner or later you will run into reentrancy problems with such approach. Loop iterators should be local variables, preferably scoped to the loop.
I need a little bit of help with using pointers in C++. Sorry to seem beginner but I really can't quite understand them. I have read the tutorial on pointers on the cplusplus.com website, so please don't suggest that.
I basically have a variable which holds the name of another variable, and I wish to access that variable through the holder one. I believe I need to use pointers, correct me if I'm wrong though.
E.g.
int a;
string b;
a = 10;
b = "a";
I need to access the variable "a" through the contents of variable "b".
Just to put this into better perspective, this is how I am using it:
int a;
a = 20;
void getVar(string name) {
cout << name;
}
getVar("a");
But as you can see, on the fifth line, that will just cout the value of name, in this case "a", but I want it to cout the value of the variable which name contains, so I want it to output "20".
Any help here would be much appreciated.
If you need to associate a name with a value, consider associative arrays otherwise known as dictionaries and maps. The Standard Template Library has std::map that you can use to associate text with a value:
#include <map>
#include <string>
std::map<std::string, int> my_map;
my_map["A"] = 20;
cout << my_map["A"] << endl;
What you are thinking of is called (Reflection) which C++ does not support. You can however use pointers to access what is in a variable it points to:
int a = 5; //int variable that stores 5
int *b = &a; //int pointer that stores address of a
(*b) = 10; //stores 10 into address that b points to (a)
cout << a; //prints 10
What you are trying to achieve is not possible in a compiled language (not considering reflection). You might accomplish something similar using a map data structure.
theMap["a"] = 20;
and a corresponding
void getVar(string key){
cout << theMap[key];
}
that can be called with
getVar("a");
Note that in this extremely simple sample theMap has to be in scope for the function, like in a class or a namespace.
If you use pointers you are just using a level of indirection not at all suited for your example. See Chads answer for instance.
Theres no real way for you to access variables by name like that unless you create some kind of container class that has a name member that you look up by. I'm not sure what this has to do with pointers though.
What you're asking for is called "reflection" or "introspection" - the ability to use design-time names for your program's objects (classes, variables, functions, etc) in run time. C++ does not support that out of the box - the design-time names are stripped upon compilation.
There are some libraries that provide that capability in C++; but there are also languages where reflection is is part of the language. Python or JavaScript, for example.
Maybe this could suit you:
int a = 5;
class b {
public:
b(int &x) { ref_ = x; }
int operator()(void) { return ref_; }
private:
int &ref_;
}
b my_b(a);
my_b() /* -> 5 */;
Your code does not use pointers. you're trying to convert a string into an identifier and print it's result, I don't know whether that's possible or not. If you intended using pointer your code should've looked like this:
int a = 20;
int* b = &a;
cout << *b;
quick fix for outputting integers only:
int a;
a = 20;
void getVar(int name) {
cout << name;
}
getVar(a);
If you need the function to work for any type of variable, maybe think about some template function.
Edit: Here is the code for the template program:
#include <iostream>
#include <string>
using namespace std;
template <class T>
void getVar(T name){
cout<<name<<endl;
}
int main()
{
string x="hee";
int y=10;
getVar(x);//outputs hee
getVar(y);//outputs 10
return 0;
}
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"... :)