Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
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
Improve this question
How do I have main() remember the value of a variable each time it is called?
i.e. if I run this program the first time I want mainCallCounter = 0, but when I is called again I want it to increase the counter
#include <iostream>
using namespace std;
static int mainCallCounter = 0;
void outputMainCallCount()
{
cout << "Main was called" << mainCallCounter << "times." << endl;
}
int main()
{
outputMainCallCount();
mainCallCounter++;
return 0;
Main is the entry point for your program. Main is called once (normally) and, when it exits, your program is torn down and cleaned up.
Obviously this means a local variable will be insufficient. You need some sort of external storage which persists longer than your application, i.e., the file system.
You can't. Each run of a program is independent. You will need to save mainCallCounter somewhere and re-read it the next time the application launches. Writing it into a file is one option, another might be something like the Windows registry or Mac OS X defaults system, etc.
All variables declared in C++ expire when the program ends. If you want to persistently remember how many times the program has been run, you will need to store that data in an external file and update it whenever you run the program.
For example:
#include <iostream>
#include <fstream>
int numTimesRun() {
std::ifstream input("counter.txt"); // assuming it exists
int numTimesRun;
input >> numTimesRun;
return numTimesRun;
}
void updateCounter() {
int counter = numTimesRun();
std::ofstream output("counter.txt");
output << counter;
}
int main() {
int timesRun = numTimesRun();
updateCounter();
/* ... */
}
Hope this helps!
Related
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 1 year ago.
Improve this question
I'm having some issue with returning vectors of objects of a class in functions because everytime my destructor erases the data twice and all the code just dies when the functions ends
here a simple code I wrote just to show my problem:
#include <iostream>
#include <vector>
using namespace std;
class identity{
public:
string name;
identity(string Name);
~identity();
};
vector<identity> function();
int main(){
function();
cout << "Hello world!";
}
identity::identity(string Name)
: name{Name}{
cout << "Object created!" << endl;
}
identity::~identity(){
cout << "Object " << name << " destroyed!" << endl;
}
vector<identity> function(){
identity me("Isaias");
}
in this case the cout "Hello world" doesn't work and the program always ends with "Object" without displaying the name like this:
Object created!
Object Isaias destroyed!
Object
and then the program just stops. I kind of fixed the problem by seting the type of the function to "void" or anything else instead of "vector" but I'd like to know why this problem occurs. Also I'm new to programming in general and in this community so I'm sorry if I'm not doing this in the right way.
I'd like to thank you all for your attention before anything and sorry again if i am messing everything up here.
vector<identity> function(){
identity me("Isaias");
}
The behaviour of the program is undefined because you don't return anything from the function even though you've declared that the function returns a vector<identity>.
To fix the bug, return a value. Example:
using namespace std::string_literals;
return {"Isaias"s};
Another bug is that you've chosen to use using namespace std, but you've declared identity which is an identifier that is already in the std namespace. This makes the program ambiguous and ill-formed.
To fix this, choose another name for the class, such that the name doesn't conflict with any of the current or future names in the std namespace. This is very difficult because there are many names in std and you cannot predict the future. There is a simpler solution though! Simply don't use using namespace std.
Third bug is that you've used std::string without including the header that defines it. The consequence is that the program may not necessarily compile in any current or future language implementation.
Solution: Include the header <string>.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am building a project that is composed of Vehicle, Showroom, and Dealership. I've built the classes, and I am testing out my method GetAveragePrice()
float Dealership::GetAveragePrice()
This method was working perfectly:
Dealership dealership("COP3503 Vehicle Emporium", 3);
dealership.AddShowroom(&showroom);
dealership.AddShowroom(&secondary);
dealership.AddShowroom(&third);
cout << "Using just the GetAveragePrice() function\n\n";
cout << "Average price of the cars in the dealership: $" << std::fixed << std::setprecision(2);
cout << dealership.GetAveragePrice();
The output would be
Using just the GetAveragePrice() function
Average price of the cars in the dealership: $27793.60
This is the expected output I wanted, but I was told I have memory leaks and must include a destructor to deallocate my *Showroom showroomList pointer (which I initialized as the following in the Dealership constructor):
this->showroomList = new Showroom[maxNumOfShowrooms];
So I write my destructor as the following:
Dealership::~Dealership()
{
delete [] showroomList;
}
Now, there aren't any memory leaks, but I don't get the expected output and an exit code 11:
Using just the GetAveragePrice() function
Process finished with exit code 11
Does anyone know why this destructor is messing up my output?
This version would delete only once by the last instance standing, in its destructor.
std::unique_ptr<ShowRoom> Dealership::showroomList;
Dealership::Dealership(size_t maxNumOfShowrooms)
:showroomList(std::unique_ptr<ShowRoom>(new Showroom[maxNumOfShowrooms]))
{
}
Dealership::~Dealership()
{
// auto deleted here, with reverse order of initialization
}
but you have a new and delete pair so you should check for deletion only once. This would need some global counter outside of class (or its static variable) and this may not be as readable as smart pointer.
If you are using multiple threads with this, then you could be better with shared_ptr and a custom deleter ([](T * ptr){delete [] ptr;}) as its second constructor parameter.
At least this way you can know if error is about new and delete.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}
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 8 years ago.
Improve this question
Yes I have read a lot of tutorials and questions and also tried a lot of combinations but it seems not to work.
My goal is not to use dynamic allocation.
My classes look like this:
Pages
Page
PMain:Page
PCam:Page
on my main when I do this:
1.
main:
Page * page;
PCam main;
main.setContext(context);
page = &main;
page->echo();
result: PCam
but when I try to create the instance inside an outside class and point it to page it fails.
2.
pages class:
Pages::Pages(Page*& page, Context& context){
this->context = &context;
PMain main;
main.setContext(*this->context);
main.echo();
// page = &main; <---
}
main:
Page * page;
Pages pages(page, context);
page->echo();
result: Page
expected result: PCam
My classes:
Page:
void Page::setContext(Context & context)
{
this->context = &context;
}
void Page::echo() //virtual
{
std::cout << "echo Page" << std::endl;
}
PMain:
void PMain::echo(){
std::cout << "echo PMain" << std::endl;}
}
PCam:
void PCam::echo(){
std::cout << "echo PCam" << std::endl;}
}
Any help would be appreciated. thanks.
Your problem, or one of them, is that this:
Pages::Pages(Page*& page, Context& context){
[...]
PMain main;
is a local stack variable. When this function returns, it ceases to exist.
If you've assigned it to a pointer, you'll get undefined behavior by using it.
My goal is not to use dynamic allocation.
Unless you have some specific reason, this is a mostly pointless goal. If you want a pointer to a stack object (i.e., one that's not dynamically allocated), that object must remain in scope as long as you use the pointer. If you can't do that, then you need to put it on the heap (i.e., dynamically allocate).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many exception handling mechanisms where they simply weren't necessary. A lot of the times the problem could have been solved in a much cleaner way using simple if statements.
For example, things like:
Invalid input
Division by zero
Wrong type
Container range check
Null pointer
Uninitialized data
... and so on.
Could someone provide an example where it would be a better approach to handle exceptions?
Exceptions become more important as your program size grows.
With a simple application return codes are probably fine. But when an error condition needs to bubble up a couple levels of the stack before being handled, it starts to make sense to use exceptions instead of passing error codes from every function.
Also, when a method already returns a value, it may not be practical or possible to return an error code from the function as well.
Sometimes using exception is cleaner. In function foo thanks to exception throwing in check function you can avoid checking what check returns what makes this function simpler:
#include<iostream>
using namespace std;
class A{
public:
int a_foo(int index){return _tab[index];}
private:
static int _tab[3];
};
int A::_tab[3]={1,2,3};
void check(int index)
{
if (index < 0 || index > 2)
throw string("invalid index");
}
void foo(A a, int index){
check(index);
cout << a.a_foo(index) << endl;
}
int main()
{
try
{
A a;
foo(a,4);
}
catch(string ex)
{
cerr << ex <<'\n';
}
}
I would use it when the consequence of some unexpected 'event' is inability for application to continue running. When it happens and you catch it, report it nicely and close the application (or whatever you think you should do in that case).