C++ Running Code from file - c++

This might seem a bit far fetched and possible off-topic (sorry if it is), but I'd like to know for sure if it is possible or not.
I am working on a Q and A program.
The text file is laid out in a Question tab Answer newline style.
My question is this: Is it possible to read an answer as a function.
Example:
Question - What time is it? / Answer - getCurrentTime()
Question - What is today's date? / Answer - getCurrentDate()
Then the program, though string parsing, knows that this is a function without an argument and calls the function getCurrentTime() or getCurrentDate() which prints the time or date respectively.

This is possible using an array of function pointers. You just load all the functions into the array. How you obtain the correct index is up to you. The only useful way I can come up with is maintain a second array containing the function names in the same positions as the functions in the function array. Then search the function name array and use the index in that array to access the correct function in the function array. If you need a better explanation leave a message. It is very late at night here and I need to work in the morning.
Barmar's solution will work to and is the better way to go about it but use function pointers.
Hope this helps
dannyhut

Related

Ocaml buffer modification specific position

I'm currently building/concatenating pretty big strings in a program I'm developing. To give some context, the full string has the size of a terminal. This happens quite a lot since I'm developing a terminal application. I found the datastructure Buffer, which seems to be the most performant way to concatenate strings with the standard library.
Is this the right choice if I also frequently need to update some part of a buffer at a specific position? Let's say character 20 to 50 ?
Is there a better way in this case?
#coredump and #kne have given good answers. I might just add that in today's world a byte is a poor representation of a character. So you might consider using an array or a bigarray.
AFAICS, there is no way to alter the contents of a Buffer.t except adding to the end. Maybe you should take a look at the module Bytes. A Bytes.t is mutable everywhere, only the length cannot change. But it seems the length you need is fixed anyway: the size of the terminal (and if the terminal window is resized you can replace the Bytes.t by a new one).

Calculate member offset of unknown type

I want to get the offset of a struct's member. I know this has been asked multiple times and the answer is always the mighty offsetof. Well, my case is a little different: I need the offset of an unknown type. That is for example:
void fill_struct(void* unknown)
{
...
}
The only thing I will know from unknown is the order in which types are set. i.e.
int
int
float
...
string
And the main problem here is align/padding, since I don't know a way to calculate it nor if there is a way at all.
This kind of question is often replied with: why would you want to do that?
For those people: I'm implementing a JSON parser in C++, and faced a problem (representing multiple type arrays), and my solution is to map the array's values into a custom struct.
I accept feedback regarding to that solution but I'm mainly interested in my question being answered

Copy Certain Portion of One Array to Another

I'm still quite new to programming -- about two months in -- so if this is a really basic question, then I apologize. Going along with that, my terminology might be completely off. If it is, I'd greatly appreciate any help you might be able to offer with telling me the proper terms. I searched around the forums here for a bit, but couldn't find anything that answered my question. If you're aware of a topic that does, then please just link it below.
Onto the question.
Let's say that I have an external text file with a bunch of information in it. The information is divided into items, each item delineated from the next by '::'. Each item is divided into four fields, each field delineated from the next by '\'.
What I want to do is take one item's information out of the text file and place it into an array called info. I want to then take info and pass it to another function. This function will create four new arrays and then portion out field 1 to array 1, field 2 to array 2, etc.
Basically, how do I take an array, take a portion of that array and give it to another variable, then copy another portion of that array and give it to another array.
Example:
The External Text File looks like the following:
26::Female::Kentucky::Trauma\\34::Male::Michigan::Elective\\85::Male::Unknown::Trauma\\18:Female::Washington::Emergent
Using fstream, I then take "26::Female:Kentucky::Trauma" and put it into an array called 'info', which is then passed to a function called Sort(char info[]).
How do I get Sort(char info[]) to take an array with "26::Female::Kentucky::Trauma" and turn it into four arrays such as:
Age: 26
Sex: Female
Location: Kentucky
Reason for Admission: Trauma
EDIT
Array 1 looks like:
26::Female::Kentucky::Trauma
I then create four char arrays called, Age, Sex, Location, Reason. How do I get 26 into the Age array, Female into the Sex array, Kentucky into the Location array, and Trauma, into the Reason array?
I know that I could do this at the stage where I'm reading in from an external file, but it seems easier to do it this way for my purposes.
Thank you for your time.
Look at the documentation for the string class. The functions find_first_of and substr will be useful. Split the string when it finds :: or //. For example, 26::Female::Kentucky::Trauma would be split into 26 and Female::Kentucky::Trauma. This sounds like it may be an assignment, so I will not give a complete solution, but this should be enough to get you going.

How do I know when a variable is accessed within my code?

I'm using VS2008 to write a program. There's one specific line in my code that causes a numerical error. It is:
Qp[j] = (Cp - Cm)/(Bp + Bm);
Qp is a std::vector. When I comment this line out, the numerical error disappears. I am going through my code line by line to find all the places that access Qp[j]. I was wondering if there was a feature in VS2008 or a linux program that wraps around the executable that can identify every line of code that reads from that section of memory (the specific element in the vector)?
I tried searching online but the keywords I used brought up results relating to global variables.
--- EDIT
Hi all. To those have responded, thank you. Just to clarify my question:
Imagine I have a vector with 5 elements. I'd like to know all the places in my code that use the value stored in element 3 at any point in time during execution. Is there an easy way to do this?
I am not sure if I understand you correctly, but if you comment out that line and the code works then maybe the problem is that line, and you don't need to check others lines.
Maybe in your case you get in the situation where Bp+Bm = 0 (division by zero error).
Qp may not have as many elements as the index j, check the size of Qp.

How do I write in-code comments and documentation in a proper way? Is there any standard for this? [closed]

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 5 years ago.
Improve this question
I want to add documentation in my code by means of comment lines.
Is there any standard format for this?
For example, consider the code below:
class Arithmetic
{
// This method adds two numbers, and returns the result.
// dbNum1 is the first number to add, and dbNum2 is second.
// The returning value is dbNum1+dbNum2.
static double AddTwoNumbers(double dbNum1, double dbNum2);
}
For this example code, is there any better way of writing the comment lines?
For c++ there isn't a standard, like javadoc, but certain documentation tools are popular and common to use. Off the top of my head, I can mention doxygen.
Doxygen also supports the familiar javadoc style, ie:
/**
This method adds two numbers, and returns the result.
#param dbNum1 is the first number to add
#param dbNum2 is second.
#return The returning value is dbNum1+dbNum2.
*/
static double AddTwoNumbers(double dbNum1, double dbNum2);
you can format your comments so later you can generate documentation. the most popular tool for this is DoxyGen
You don't want to write too much. Suppose you write comments for a function that, in the future, saves you ten minutes of time understanding your code. Great. But suppose your comments are so verbose that it takes five minutes to write them and then, later, five minutes to read them. Then you've saved yourself zero time. Not so good.
You don't want to write too little, either. If code goes on for a page or two without something breaking down what's going on, well, I hope that code is clear as crystal, because otherwise you're wasting future time.
And you don't want to comment in stupid ways. When people first start writing comments, they often get hyper and write things like:
// Now we increase Number_aliens_on_screen by one.
Number_aliens_on_screen = Number_aliens_on_screen + 1;
Uhmmm, duh. If something is so obvious, it doesn't need a comment. And if your code is such a tangle that you need a comment for every single line of it, you'd probably profit from making it simpler in other ways first. Comments don't just save time, they cost it. They take time to read, and they spread out the actual code on the screen, so you can have less of it on your monitor to inspect at one time.
And, while we're at it, don't ever do this:
Short get_current_score()
{
[insert a whole bunch of code here.]
return [some value];
// Now we're done.
}
Oh? We're done? Thanks for letting me know. That big right bracket and the infinite expanse of empty space beyond really didn't tip me off to that. And you don't need a comment before the return statement saying, "Now we return a value," either.
So, if you are writing code, in the absence of a boss or a company policy telling you what to do, how do you comment it? Well, what I do for code I am stuck with maintaining myself is write an introduction. When I return to a procedure I forgot that I wrote, I want to see an explanation for what is going on. Once I understand what the machinery is doing, it becomes infinitely easier to understand the actual coding. This generally involves:
A few sentences before the procedure/function saying what it does.
A description of the values being passed into it.
If a function, a description of what it returns.
Inside the procedure/function, comments that split the code up into shorter tasks.
For chunks of code that seem thorny, a quick explanation of what is happening.
So we need a description at the beginning and a few signposts inside explaining the road taken. Doing this is very quick, and it saves a ton of time in the long run.
Here is an example from the theoretical Kill Bad Aliens. Consider the object representing the bullet the player fires. You will frequently have to call a function to move it upwards and see if it hits anything. I would probably code it something like this:
// This procedure moves the bullet upwards. It's called
//NUM_BULLET_MOVES_PER_SECOND times per second. It returns TRUE if the
//bullet is to be erased (because it hit a target or the top of the screen) and FALSE
//otherwise.
Boolean player_bullet::move_it()
{
Boolean is_destroyed = FALSE;
// Calculate the bullet's new position.
[Small chunk of code.]
// See if an enemy is in the new position. If so, call enemy destruction call and
// set is_destroyed to TRUE
[small chunk of code]
// See if bullet hits top of screen. If so, set is_destroyed to TRUE
[Small chunk of code.]
// Change bullet's position.
[Small chunk of code.]
Return is_destroyed;
}
If the code is clean enough, this sort of commenting should be sufficient. And it will save plenty of time the dozen times I return to this function to fix a dumb mistake I made.
Refered from: here
Doxygen and other similar tools can help with this. Basically you write comments according to some pre-defined style and from that HTML/PDF/etc. documentation is extracted.