Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was working on a project and I've had a question: when I call a class that contain a string str, does the code create a string every time or it use the string I've already created?
For example:
#include <iostream>
using namespace std;
class exClass {
public:
void exVoid ( string valueStr )
{
str = "Hi";
cout << str;
}
private:
string str;
};
int main()
{
exClass myClass;
string stringMain;
while (1)
{
cout << "Insert value of str: ";
cin >> stringMain;
myClass.exVoid(stringMain);
}
}
so the question is: every time I call exClass, the class create the string str or it do that only once (when I call it for the first time)?
Following the flow of the program:
First you create an instance of exClass named myClass. This happens once.
Then you create a string named stringMain. This also happens once.
After that, you have an endless loop while(1). Inside this loop you:
Print on the output
Get input
Call function exVoid()
So, you create one instance of class exClass with one member str and use the same str (through your function) endlessly inside your loop.
Something to think about is the function argument. You never really use it. For it to have meaning in you code, you can do something like:
void exVoid ( string valueStr )
{
str = valueStr;
cout << str;
}
Yes, you're creating a copy of your input string every time you call exVoid. You can make it more efficient if you use a reference:
void exVoid(const std::string &value) {
...
}
The way you're calling it from main, you're thus passing a reference to stringMain, but by making it const, you know your method won't mess with it.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 15 days ago.
Improve this question
I am trying to create multiple files according to a filename in cpp. Using ofstream for that, I could not achieve it for now.
I'd appreciate if anyone can help me with that.
I am writing down here:
static std::ofstream text1;
static std::ofstream text2;
class trial{
public:
if(situation == true) {
document_type = text1;
}
if(situation == false) {
document_type = text2;
}
document_type << "hello world" << "\n";
}
ofstream object as variable.
Assignment copies the objects, and it's not possible to create copies of streams. You can only have reference to streams, and you can't reassign references.
Instead I suggest you pass a reference to the wanted stream to the trial constructor instead, and store the reference in the object:
struct trial
{
trial(std::ostream& output)
: output_{ output }
{
}
void function()
{
output_ << "Hello!\n";
}
std::ostream& output_;
};
int main()
{
bool condition = ...; // TODO: Actual condition
trial trial_object(condition ? text1 : text2);
trial_object.function();
}
Also note that I use plain std::ostream in the class, which allows you to use any output stream, not only files.
You can't use statements at class scope, only declarations.
In any case, you need to use a reference variable for what you are attempting, eg:
std::ofstream& document_type = situation ? text1 : text2;
document_type << "hello world" << "\n";
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have class
class Item
{
private:
string name;
public:
void set_data()
{
getline(cin, name);
}
}
From the main function I am setting the value of the name once, but when I want to give it another value, I can't. I mean that the second time when I call the function from the same object, it does nothing.
First of all, in C++ your implementation should be separate from the declaration unless you are using templates which you are not. This is not Java.
Second, your sample code is missing a closing brace. I have submitted an edit to add it and improve your code formatting.
That aside, the following implementation works for me:
Item.h
class Item
{
private:
std::string name;
public:
void set_data();
void printName();
};
Item.cpp
void Item::set_data()
{
std::cout << "Type name and hit return: " << std::endl;
getline(std::cin, name);
}
void Item::printName()
{
std::cout << "Name is : " << name << std::endl;
}
main.cpp
// Entry point
int main(int argc, char** argv)
{
// Yes I thought I would mix things up and use new instead of Item i; So shoot me.
Item * i = new Item();
i->set_data();
i->printName();
i->set_data();
i->printName();
delete i;
return 0;
}
The application will wait at both calls to set_data() for me to type something in and hit return. Then it continues as normal. I added a text prompt so it is less confusing to see in the console. I get this:
Does this in some way answer your question? If you are doing something else in main() then try stripping it out back to just this simple action then add the other stuff back in until you find the bit that introduces the problem.
UPDATE:
As prompted by the comments below, if you put std::cin >> before another call to getline() it will read the first word from the stream and leave the rest of your string and the \n character in there which getline() uses for its delimiter. So next time you call getline() it will automatically extract the rest of the string from the stream without requesting user input. I guess this is probably what you are seeing.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to use vector to store all Record. The Record class contains student and their age. It supposes to get the command and then call the specific method. However, when I compile it, it said "t is not declared". However, I have already declared as table t. How can I access the private vector without changing the visibility.
class student{
public:
int id;
string name;
student();
student(int,string);
};
class Record{
public:
student student;
int age;
};
class table{
public:
void Insert(student x,int y);
void Print(table t)
private:
vector <Record> records;
};
void Insert(student x,int y){
Record r;
r.student=x;
r.grade=y;
t.records.push_back(r);
}
void Print(table t){
sort( t.record.begin() , t.record.end() );
vector<Record>::iterator itr;
for( itr = t.record.begin() ; itr != t.record.end() ; itr++ )
cout << (*itr).student.id << '\t' << (*itr).student.name << '\t' << (*itr).age << endl;
}
int main (){
student x;
table t;
string command,name;
int id,age;
while ( cin >> command ){
if (command=="Insert"){
cin >> id >> name>> grade;
student s(id,name);
t.InsertStudent(s,grade);
}else if (command == "Print"){
t.Print(t);
}else{return 0;
}
}
The error message is:
t was not declared in this scope in t.records.push_back(r);
I have capitalized the class name and the problem still exist.
There are a significant number of problems with this code. So we'll address the 3 mistakes most closely related to your question: How can I access the private vector without changing the visibility?
You are calling: t.InsertStudent(s,grade). Since you declare table t, that will try to call class table's InsertStudent method. Which there isn't one. You probably intended to call the Insert method.
You define the function void Insert(student x,int y) which was likely intended as the method void table::Insert(student, int y). Note the class scoping on the definition. Alternatively, you could remove the declaration, and just use the definition directly in class scope.
You are trying to call t.records.push_back(r) where t is not a global object that this function would have access to. But presuming from 2 that you intended to define this as a method you would not use an object name to access member variables, instead you could directly access the member variables: records.push_back(r)
I've tried to briefly explain how to fix stuff, but there are some underlying conceptual problems here that need to be addressed, which probably can't be addressed in a couple sentences. Please at least read through: http://www.cplusplus.com/doc/tutorial/classes/ before asking follow up questions. If any of my answer remains unclear after reading through that, feel free to comment below.
As far as other errors in the code start by looking over the line that the compiler issues the waning on. If you can't solve it using that feel free to open a new question posting the code and error.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I had the below C++ question in the recent interview but could not do. Please help.
Given a company structure where every employee reports to a superior, all the way up to the CEO, how would you print out all the employees that a particular individual oversees?
Write a method that implements this, given the below:
// Employee object contains a string denoting the.
// employee name, and an array containing
// employees who report to this employee
Employee {
String name;
Employee[] employees;
}
I have seen and understand the recursive function. But I have not encounter such a recursive object/structure like this one.
My new question is how can an object is created and initialized from this class/structure since it is recursive?
Thank you very much again.
With the information given it is very hard to answer (and question should probably be set on hold). Anyway...
I think a recursive approach is the answer. You need a function that can take a name, search the full employee list for that name and then call the function again for every employee in the local array. Something like:
void doit(Employee& e)
{
// Print e.name
// For each employee tmp in e.employees (i.e. local array)
doit(tmp);
}
Note - this requires that there are no loops in manager-employee arrays. If there is this will be an endless loop. So this is a dangerous approach.
EDIT:
This is added due to the comment from OP.
As indicated above the question is vague and doesn't really give sufficient information to provide a good answer. The struct given in the question is not valid C++ and there is no description of how the company wide list of employees are maintained.
However to keep it simple, the printing could look like this:
struct Employee
{
void PrintAllReportingEmployee(int level)
{
cout << string(4*level, ' ') << name << endl;
level++;
for (auto& e : employeesDirectlyReportingToThisEmployee)
{
e.PrintAllReportingEmployee(level);
}
}
string name;
vector<Employee> employeesDirectlyReportingToThisEmployee;
};
// Code in some print function:
// Step 1 - find the relevant employee
Employee tmp = SomeFunctionReturningAnEmployeeBasedOnName("NameOfPerson");
// Step 2 - print all employees reporting directly and indirectly
tmp.PrintAllReportingEmployee(0);
This assumes a single top-level Employee (e.g. director) with a vector of employees directly reporting to the director. Each of these would then have a vector of employees reporting to them and so. So it is kind of an tree structure.
Note, if I should design a employee db, I would not go with such a solution.
Who ever asked the question was looking for an answer with something to do with class inheritance. So a class Persion is extended by Employee where Person is also extended by Manager etc etc where they all share some similar properties but not everything.
This means that your code can be expanded upon by other programmers and one change can fix many different classes!
Although this code does not demonstrate class inheritance, it will work.
/*
THE OUTPUT:
Jacobs-MacBook-Pro:~ jacob$ ./employee
Foo McGoo
Bar Too
Jacobs-MacBook-Pro:~ jacob$
*/
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::endl;
/* define class (this should be in a header file) */
class Employee{
public:
//Variables
string Name;
//Functions
Employee(const string&); //constructor
void AddCoWorker(const Employee&);
void ShowCoWorkers();
private:
vector<Employee> employees;
}; //Note the semicolon
//Entry point
int main(int argc, char **argv){
Employee foo("Foo McGoo");
Employee bar("Bar Too");
Employee me("Bevis");
me.AddCoWorker(foo);
me.AddCoWorker(bar);
me.ShowCoWorkers();
return 0;
}
//Class functions (should be in a separate cpp file)
Employee::Employee(const string& name){
this->Name = name;
}
void Employee::AddCoWorker(const Employee &e){
this->employees.push_back(e);
}
void Employee::ShowCoWorkers(){
int count = this->employees.size();
for(int i = 0; i < count; i++){
//Print the names of each co worker on separate lines
cout << this->employees[i].Name << endl;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to programming and I can only use C++. I have been working on an RPG, and for some reason I can't get the program to print out the value that I set a string to. I started by defining the string "weapon" in void main.
void main()
{
string weapon;
cin >> weapon;
if(weapon = "A")
{
weapon == "sword";
}
}
I had the code sort of like this and I had a function above it that uses "weapon" (which was set to sword as you can see from the code above) at the end of something that I had it print out, but that was in the function (which was above the void main) so in order to get both to be defined variables I had to define them in both the void main and the function, but when I do that, nothing appears in the program when it's run. I had everything written correctly (what I put above is just an example) but the only way that it doesn't create an error is by defining it in both parts of the code. It says that one of them hasn't been defined yet so I defined it both the function and the void main. Why isn't it working? How do I fix it?
Thanks
P.S. I did include the string library and namespace.
void main() is illegal. It must be int main(), though some compilers will erroneously accept void main().
if(weapon = "A")
{
weapon == "sword";
}
It looks like you have this backwards. The single operator= sets weapon to the constant "A", regardless of what the user entered. The comparison operator== compares weapon with the constant "sword" and promptly discards that result. Perhaps you meant to use comparison in the if and assignment in the body of the if?
You're using = where you need ==, and vice versa. Should be:
if(weapon == "A") { weapon = "sword"; }
At least as I read it, you have code vaguely like this:
void f() {
string weapon;
cout << weapon;
}
int main(){
string weapon = "sword";
f();
}
...and the problem is that the value you're assigning to weapon in main isn't being used used when you call f.
Assuming that's roughly correct, what you're seeing is normal, expected behavior. The weapon you've defined in main is a separate variable from the weapon you define in f. Assigning a value to one has no effect on the other.
To get the desired effect, you need to "pass" the value from one to the other as a parameter:
void f(string w) {
cout << w;
}
int main() {
string weapon = "sword";
f(weapon);
}
This way, calling f gives it a copy of the current value that the weapon in main has been assigned, so f can use that same value.
You should look up for online tutorial, programming in C++. That is a good place to get started. Or buy a book on C++ programming.